Reputation: 31
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
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
Reputation: 409176
You actually have two problems with your code:
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
.
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