I have a std::list full of objects. Whenever I add a object, I want to store that objects index in the list, so later on I can remove it from the list.
What I want to do in pseudo code
myList.pushBack(element);
int index = myList.getIndexOfLastElement();
myList.erase(index);
For performance reasons I can't search by value.
To clarify: I have element a(index 0), b(index 1), c(index 2), d(index 3)
If I delete element b, I still want to be able to access c by 2.
I'd suggest using std::list::iterator
instead of integer indices. std::list::erase()
does not invalidate iterators.
auto index = myList.insert(myList.end(), element);
myList.erase(index);
You'll need to map
the index
s to the iterator for that element. Something like:
auto pos = myList.cbegin();
map<int, decltype(pos)> m;
// bump pos for every myList.pushBack(element);
int index = myList.getIndexOfLastElement();
m[index] = pos;
// then you can erase with
myList.erase(m[index]);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.