Arch1tect
Arch1tect

Reputation: 4281

Erase an element in std::list using pointer not iterator

As the title stated, I'm using std::list. I have objects in master.list. Then I use a std::priority_queue or whatever, called sortedList to store pointers to the objects in my master.list and it's all sorted in this sortedList now. Because it's sorted, I can remove them using sortedList.pop().

The question is how can I elegantly remove objects back in my original master.list

I want to use erase, but it only take iterator while I just have pointer. Because I want the speed, I really don't want to use remove here.

Upvotes: 0

Views: 188

Answers (1)

Chris Hayden
Chris Hayden

Reputation: 1144

Why not store iterators in the priority queue instead of raw pointers? Since you are using list you do not need to worry about iterator invalidation. Then you can just use std::list::erase. The overhead of storing an iterator should be negligible since it just holds a pointer to the list node.

typedef std::list<T> MyListT;
typedef std::priority_queue<MyListT::iterator> MyQueueT;

MyListT myList;
MyQueueT myQueue;

myList.push_front(T());
myQueue.push_back(myList.begin());

// Later...

MyListT::iterator itr = myQueue.front();
myQueue.pop_back();
myList.erase(itr);

Upvotes: 3

Related Questions