I want to modify the <queue>
STL so that it can find any element from the priority_queue
, then delete it from the pq
. The code is based on the answer by alexm from How to remove element not at top from priority_queue?
However, what I want to achieve is more complicated: the element in the priority_queue
is pair<char, double>
, and I want to achieve a min-heap. Thus, I modified the code as below:
#include <iostream>
#include <queue>
using namespace std;
using item_type = pair<char, double>;
template<typename T>
class custom_priority_queue : public priority_queue<T, vector<T>, greater<>> {
public:
bool eleExist(const T& value) {
auto it = lower_bound(this->c.begin(), this->c.end(), value);
if (it != this->c.end())
return true;
else
return false;
}
bool remove(const T& value) {
auto it = lower_bound(this->c.begin(), this->c.end(), value);
if (it != this->c.end()) {
this->c.erase(it);
make_heap(this->c.begin(), this->c.end(), this->comp);
return true;
}
else {
return false;
}
}
};
int main() {
custom_priority_queue<item_type> pq;
// use list to fill priority_queue later
// larger number means higher priority
initializer_list<item_type> il {
{'A', 10},
{'B', 12},
{'H', 12}
};
// iterator through list to fill into priority_queue
for (const auto& item : il) {
pq.emplace(item);
}
if (pq.eleExist({'A', 10})) {
cout << "A exists. Thus remove it" << endl;
pq.remove({'A', 10});
}
else
cout << "A doens't exist" << endl;
// print priority_queue
cout << "Currently in priority queue:" << endl;
while (!pq.empty()) {
cout << pq.top().first << ": " << pq.top().second << endl;
pq.pop();
}
cout << endl;
return 0;
}
Unfortunately, I can only use eleExist
and remove
functions with the full pair in my main
function. What I really want to achieve is, to find element in priority_queue
based on the 1st element in pair
, and is able to delete the pair
element based on the eleExist
function. How do I modify my derived class custom_priority_queue
to achieve that?
Thanks.