c++ - C++ 中有什么方法可以在保留迭代器的情况下将项目从一个 std::map 移动到另一个?
问题描述
这是我想要实现的:
假设我有 2 个std::map<int,int>
装有物品的容器
m1 = {{1,1}, {2,2}, {3,3}};
m2 = {{4,4}, {5,5}};
我有一个迭代器引用m1
( {2,2}
)中的第二个项目
auto it = m1.find(2);
现在我想将带有键 2 的项目从m1
to移动m2
,因此迭代器应该在不重新分配的情况下it
引用正确的元素。m2
搬家前:
m1 = {{1,1}, {2,2}, {3,3}}
^
it
m2 = {{4,4}, {5,5}}
搬家后:
m1 = {{1,1}, {3,3}}
m2 = {{2,2}, {4,4}, {5,5}}
^
it
到目前为止,我已经编写了执行我想要的代码:
std::map<int,int> m1 {{1,1}, {2,2}, {3,3}};
std::map<int,int> m2 {{4,4}, {5,5}};
auto it = m1.find(2);
m2.insert(std::move(m1.extract(m1.find(2))));
但是规范说引用提取项目的迭代器无效。那么使用方法移动元素后使用迭代器是否安全extract
?或者有没有其他方法可以实现我想要的?
我会很感激任何想法,谢谢。
解决方案
不确定您如何实际填充这些地图,而是在没有任何更大背景的情况下出现在我脑海中的幼稚解决方案:
#include <iostream>
#include <vector>
using namespace std;
using MyCustomMap = std::vector<std::pair<int, int>*>;
std::pair<int, int>* findInMyCustomMap(const MyCustomMap& my_map, int key) {
for(const auto& i : my_map) {
if(i->first == key) {
return i;
}
}
}
int main()
{
std::pair<int, int> el1{1,1};
std::pair<int, int> el2{2,2};
std::pair<int, int> el3{3,3};
std::pair<int, int> el4{4,4};
std::pair<int, int> el5{5,5};
MyCustomMap m1{{&el1, &el2, &el3}};
MyCustomMap m2{{&el4, &el5}};
const auto it = findInMyCustomMap(m1, 2);
m2.insert(m2.begin(), it);
std::cout << it->second << std::endl;
}
https://onlinegdb.com/SJL1ma_xP
不过,请记住所引用对象的范围/生命周期。
推荐阅读
- rust - #[automatically_derived] 是什么意思?
- python - 使用 gensim 加载 FastText 的法语预训练模型时出错
- php-7 - Laravel 5.6:无法访问构造函数内的类变量
- spring - Spring 和 Camel 在单元测试中排除路由
- r - 在 R 中交换两位数字的子集数据帧
- angular - Observable 内部的 Angular 单元测试 EventEmitter
- php - 无法在 CDetailView Yii 1.1 中显示图片
- multithreading - 不使用条件变量或睡眠函数的周期性线程唤醒
- javascript - 将 bool 值转换为其字符串表示形式的最短方法(例如 'true')
- php - 将 Z/OS 许可证添加到云上已安装的 ODBC Cli 驱动程序