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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With