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. eg 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());
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.
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 (ie the key didn't previously exist in the map)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.