How can I configure std::priority_queue to ignore duplicates?
How can I configure std::priority_queue
to ignore duplicates?
When I add a key that is already contained then this new one should be ignored. (In my case, the priority for the old and the new one will always be exactly the 开发者_如何学JAVAsame.)
Complexity-wise it should not make a difference: It will try to insert at the appropriate location, find the existing one there and do nothing. The question is just if std::priority_queue
is configurable in that way.
You can implement a priority_queue out of an STL set.
Implementing a priority queue that can be iterated over in C++
As Aater mentioned you could use an stl set as a priority queue.
Another option is to add duplicates to the priority queue, but when popping items off the queue, keep track of the previous value and ignore repeated values. For example, here's processing all values on a priority queue while ignoring duplicates
priority_queue<int> pq = /* values */;
int curr = 0;
int prev = 0;
bool first = true;
while(isplit < target) {
prev = curr;
curr = pq.top();
pq.pop();
if (!first && prev == curr) {
continue;
}
first = false;
// do something with curr
}
精彩评论