Jay Kim
Jay Kim

Reputation: 843

iterating through multiset of structs

I'm not getting the syntax right. Lets say I have this...

#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;
}

How do i access int bar and string test of each element inside the for loop?

Thanks!

Upvotes: 1

Views: 2539

Answers (2)

Sarfaraz Nawaz
Sarfaraz Nawaz

Reputation: 361612

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;
}

In C++11, you could do this instead:

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

Upvotes: 2

ulidtko
ulidtko

Reputation: 15590

There is a good mnemonic rule that an iterator is a safe C++ abstraction for pointer.

So basically you access the elements through dereferencing syntax:

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

Upvotes: 2

Related Questions