0

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());
ks1322
  • 33,961
  • 14
  • 109
  • 164
Kashif
  • 3
  • 1

2 Answers2

1
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.

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
Miguel Angel
  • 630
  • 7
  • 18
0

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)

MartinStettner
  • 28,719
  • 15
  • 79
  • 106
  • thanks, but the map is updated. and i would not necessarily be using the last inserted pair in next line. should i reload the map and refresh the iterator? – Kashif Sep 15 '11 at 09:03