Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ map over an iterator?

Tags:

c++

iterator

map

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.

like image 921
user620189 Avatar asked Nov 27 '22 18:11

user620189


1 Answers

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.

like image 66
Platinum Azure Avatar answered Nov 30 '22 06:11

Platinum Azure