开发者

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 varia开发者_C百科ble. 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());


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 (i.e. the key didn't previously exist in the map)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜