BlueFlame
BlueFlame

Reputation: 31

Proper usage of iterator for map in c++

I have this struct:

struct next
{
    string name;
    bool isStart;
    next(){
        isStart = true;
    }
};

and this map:

map<string, next> loc;

Only one "value" entry in the map has isStart set to true (rest are set to false in code I didn't post here). I need to iterate through the map and find out which one has isStart set to true (its corresponding name). I tried this:

string start;
map<string, next>::iterator it;
for(it=loc.begin(); it!=loc.end(); it++){
    if(*it.isStart){
        start = *it.name;
        break;
    }
}

and of course it didn't work. The iterator gives me a reference to the a particular map entry (the whole key value pair) but I can't figure out how to get to it's corresponding value entry. Am I iterating it wrong?

Upvotes: 0

Views: 79

Answers (2)

erg
erg

Reputation: 1652

As this is about proper usage of iterators, I would recommend to use a const_iterator if you do not intend to modify anything, but just find the corresponding element and copy the key.

map<string, next>::const_iterator it;

Upvotes: 0

Some programmer dude
Some programmer dude

Reputation: 409176

You actually have two problems with your code:

  1. The first is that the dereference operator * have lower operator precedence than the selector operator ., so the compiler thinks you are doing *(it.isStart).

    To solve this either use parentheses like (*it).isStart or the pointer-selector -> like it->isStart.

  2. The second problem is that the iterator, when dereferenced, gives you a std::pair, which means you have to do e.g.

     if (it->second.isStart)
    

You might want to read e.g. this std::map reference.

Upvotes: 3

Related Questions