[英]Is there any way in C++ to move item from one std::map to another with preserving the iterators?
這是我想要實現的:
假設我有 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
移動到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
不過,請記住所引用對象的范圍/生命周期。
std::map::insert()
返回插入元素的iterator
。 沒有辦法讓你的it
變量神奇地從m1
指向m2
,特別是因為std::map::extract()
“使提取元素的迭代器無效”,所以你必須在提取后重新分配it
,例如:
auto it = m1.find(2);
if (it != m1.end())
it = m2.insert(m1.extract(it)).position;
或者:
auto it = m2.insert(m1.extract(2)).position;
由於您希望it
指向移入m2
的元素,因此您必須使用insert()
返回給您的新iterator
。 舊的迭代器已經失效,不能再使用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.