C++ map over an iterator?
Solution 1
You can get the value by dereferencing the iterator (as if it were a pointer). This returns a key/value pair type, which has a member second
that has the value:
map<string, int>::iterator itr = mValue.find(inName);
int value = itr->second;
The reason an iterator is returned is because the end()
iterator is returned when a match couldn't be found:
map<string, int>::iterator itr = mValue.find(inName);
if (itr == mValue.end())
{
throw "No value could be found.";
}
int value = itr->second;
Hopefully that makes some sense.
Solution 2
What happens if that key does not exist in the map? What would you return for find
? With an iterator, you can return mValue.end()
. In addition, iterators allow iteration- an int doesn't.
Solution 3
mValue.find(inName)
returns an iterator to the position in the map at which the key inName
is located. If you just want the corresponding value, you can use mValue[inName]
.
Solution 4
int value = mValue.find(inName)->second;
provided find didn't return mValue.end()
Solution 5
Why are they defining an iterator.
Because that's what the map .find() function returns, an iterator containing the key and value. Or it returns mValue.end() if the value was not found, which is useful as you can test for whether the value was found in the map or not.
to get the value you can do:
map<string, int>::iterator itr = mValue.find(inName);
if(itr != map.end()) {
int value = itr->second;
// use value
}
Is it not possible to say something like int value = mValue.find(inName)
No, std::map does not have a function like that. (and if it did, it'd have to throw an exception in the case the value was not found)
user620189
Updated on June 05, 2022Comments
-
user620189 almost 2 years
I am looking over some code that looks something like this
map<string, int>::iterator itr = mValue.find(inName);
Why are they defining an iterator. Is it not possible to say something like
int value = mValue.find(inName)
Thanks.
-
Michael Krelin - hacker about 13 yearsThis is non-const, though and will create a map entry if it's not there. (not that the original code is less disastrous in case there's no value).
-
Sjoerd about 13 yearsIt doesn't retun NULL when not found. So -1 for a wrong answer.
-
phooji about 13 yearsSeconded for not removing the answer after the initial downvote.
-
dfan about 13 yearsIt does have a function like that (
operator[]
), but it has the additional side effect of inserting the key in the map if it doesn't already exist (which gets around having to throw an exception). -
mukeshkumar about 13 years@phooji: Its not possible for everybody to be online all the time. If you feel you want to downvote just because the person did not remove the answer you are free to do so.
-
mukeshkumar about 13 years@Sjoerd: I think i missed this part...i've used the expression iter == map.end() a number of times. Anyways, thanks for pointing that out.