Kashif
Kashif

Reputation: 3

C++ MapType::iterator using updated value

In my C++ code, I access a map through iterator. Update the map if necessary and re-assign it to class variable. In proceeding statements, I want to use updated map value again. Should I load the map again, refresh the iterator? etc. e.g. the map is:

MapType tbl = device->trust();
MapType::iterator iter_trust = tbl.begin();
tbl.insert(std::pair<int, double> (node->getId().id(), 0.1));

to execute the following on updated value, what should I do?

iter_trust = tbl.find(node->getId().id());

Upvotes: 0

Views: 992

Answers (2)

Miguel Angel
Miguel Angel

Reputation: 640

MapType tbl = device->trust();
MapType::iterator iter_trust = tbl.find(node->getId().id());

if (iter_trust == tbl.end()) {
   tbl.insert(std::make_pair(node->getId().id(), 0.1));
   iter_trust = tbl.find(node->getId().id());
}
else {
   tbl[node->getId().id()] = 0.1;
}

So you'll be sure you upgrade.

Upvotes: 1

MartinStettner
MartinStettner

Reputation: 29174

std::map::insert returns an iterator to the newly inserted element. If your MapType is some typedef to a std::map, you can do

std::pair<MapType::iterator, bool> result = tbl.insert(std::make_pair(node->getId().id(), 0.1));
MapType::iterator iter_trust = result.first;

and go on.

Btw, note the use of std::make_pair, which is usually simpler than using the pair constructor directly.

Also, note that map::insert returns a pair of an iterator and a boolean. The iterator gives you the position of the inserted object, the boolean indicates if the insertion was successful (i.e. the key didn't previously exist in the map)

Upvotes: 0

Related Questions