[英]C++ MapType::iterator using updated value
In my C++ code, I access a map through iterator. 在我的C ++代码中,我通过迭代器访问地图。 Update the map if necessary and re-assign it to class variable.
如有必要,请更新地图,然后将其重新分配给class变量。 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. std::map::insert
将迭代器返回到新插入的元素。 If your MapType
is some typedef to a std::map
, you can do 如果您的
MapType
是std::map
typedef,则可以执行
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. 顺便说一句,请注意
std::make_pair
的使用,这通常比直接使用pair
构造函数简单。
Also, note that map::insert
returns a pair of an iterator and a boolean. 另外,请注意
map::insert
返回一对迭代器和一个布尔值。 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) 迭代器为您提供了插入对象的位置,布尔值指示插入是否成功(即该键先前在映射中不存在)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.