如何在C ++中将迭代器存储在Map中

时间:2016-12-08 19:46:17

标签: c++ iterator

考虑我有一个整数列表。我试图为每个存储迭代器 地图列表中的整数。这种快速查找元素的方法,我可以使用迭代器来获取元素。

但为什么不能增加迭代器并将其存储在我的地图中呢?

list<int> myList;
unordered_map<int, list<int>::iterator> myMap;
int count = 0;

myList.push_back(1);
//myMap[1] = myList.begin() + count;    <--- Why can't I do this

// Alternatively I can do something like this
auto tmpItr1 = myList.begin();
advance(tmpItr1, count);
myMap[1] = tmpItr1;
count++;

myList.push_back(2);
//myMap[2] = myList.begin() + count;    <--- Why can't I do this
auto tmpItr2 = myList.begin();
advance(tmpItr2, count);
myMap[2] = tmpItr2;
count++;

myList.push_back(3);
//myMap[3] = myList.begin() + count;    <--- Why can't I do this
auto tmpItr3 = myList.begin();
advance(tmpItr3, count);
myMap[3] = tmpItr3;
count++;

// Delte 2 from the list
auto mapItr = myMap.find(2);
if (mapItr != myMap.end())
{
    cout << "Delte: " << *(mapItr->second) << endl;
    myList.erase(mapItr->second);
}

正在使用std :: advance正确的方法吗?

0 个答案:

没有答案