如何从源地图中正确查找元素并将其插入另一个地图?
std::map<int, std::shared_prt<Obj>> src_map
std::map<int, std::shared_prt<Obj>> target_map
int key = 6;
auto found_elem = src_map.find(key);
if (found_elem != src_map.end()) {
if (target_map.find(key) == target_map.end()) {
target_map.insert(found_elem ); <---- How to correctly insert found element from src_map to target_map
}
}
Run Code Online (Sandbox Code Playgroud)
target_map.insert(found_elem);
Run Code Online (Sandbox Code Playgroud)
found_elem 是一个迭代器,你需要插入它引用的值:
target_map.insert(*found_elem);
Run Code Online (Sandbox Code Playgroud)
这也可以更有效地完成:
if (target_map.find(key) == target_map.end()) {
target_map.insert(found_elem);
}
Run Code Online (Sandbox Code Playgroud)
你做两次查找.一次find又一次地进入insert.
最好只是尝试插入它,如果你需要知道它是否插入检查返回值:
auto inserted = target_map.insert(*found_elem);
// inserted.first is the iterator to the element with the desired key
// inserted.second is true if a new element was inserted, false if the key already existed
Run Code Online (Sandbox Code Playgroud)
将其放入地图的其他选项是找到它所属的位置,然后插入该位置,如果它已经存在:
auto lower = target_map.lower_bound(key);
if (lower == target_map.end() || lower->first != key) {
target_map.insert(lower, *found_elem);
}
Run Code Online (Sandbox Code Playgroud)
另一种选择是:
auto& val = target_map[found_elem->first];
if (!val)
val = found_elem->second;
Run Code Online (Sandbox Code Playgroud)
但这并不完全相同,因为如果键已经存在于地图中,shared_ptr并且值为空,那么该值将被替换.取决于您是否可以在地图中使用可能不适合您的程序的空shared_ptr对象.
另一个意义略有不同的是:
target_map[found_elem->first] = found_elem->second;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
183 次 |
| 最近记录: |