迭代多结构的结构

时间:2012-03-22 16:33:45

标签: c++ stl set

我没有正确的语法。让我说我有这个......

#include <set>
...    
struct foo{
    int bar;
    string test;
};

struct comp{
    inline bool operator()(const foo& left,const foo& right){
        return left.bar < right.bar;
    }
};

int main(){
    std::multiset<foo,comp> fooset;
    std::multiset<foo,comp>::iterator it;

    ...//insert into fooset

    for (it = fooset.begin(); it != fooset.end(); it++){
        //how do i access int bar and string test of each element?
    }
    return 0;
}

如何访问for循环中每个元素的int bar和字符串测试?

谢谢!

2 个答案:

答案 0 :(得分:2)

有一个很好的助记符规则,迭代器是指针的安全C ++抽象。

所以基本上你通过解除引用语法来访问元素:

(*it).bar = 0;
it->test = "";

答案 1 :(得分:2)

for (it = fooset.begin(); it != fooset.end(); it++)
{
      foo const & f = *it; //const is needed if it is C++11
      //use f, e.g
      std:: cout << f.bar <<", " << f.test << std::endl;
}

在C ++ 11中,您可以这样做:

for(foo const & f : fooset)
{
      //use f, e.g
      std:: cout << f.bar <<", " << f.test << std::endl;
}
相关问题