Consider I have a list of integers. I am trying to store the iterator for each integer in the list on a map. This way to quickly find an element, I can use the iterator to get to the element.
But why can't increment the iterator and store it in my map?
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);
}
Is using std::advance the right approach for this?