首页 > 解决方案 > C++ 中有什么方法可以在保留迭代器的情况下将项目从一个 std::map 移动到另一个?

问题描述

这是我想要实现的:

假设我有 2 个std::map<int,int>装有物品的容器

我有一个迭代器引用m1( {2,2})中的第二个项目

auto it = m1.find(2);

现在我想将带有键 2 的项目从m1to移动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?或者有没有其他方法可以实现我想要的?

我会很感激任何想法,谢谢。

标签: c++dictionaryiteratorextractmove

解决方案


不确定您如何实际填充这些地图,而是在没有任何更大背景的情况下出现在我脑海中的幼稚解决方案:

#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

不过,请记住所引用对象的范围/生命周期。


推荐阅读