How to find an element in a priority queue of C++11 and access the respective element? As for the following example: What would be the best to check the existence of an element in the priority queue Q and access it. Is it also possible to edit it ?
Intention: Writing an application, in which I have to check whether a particular object has been inserted into priority queue or not. If it is being inserted, then I need to access that particular object and possibly update it.
#include <iostream>
#include <vector>
#include <string>
#include <queue>
struct Person {
int val;
std::string y;
bool operator()(const Person& lhs, const Person& rhs) const
{
return lhs.val > rhs.val;
}
};
int main () {
std::vector<int> data = {5,4,3,2,1};
Person X1,X2,X3,X4,X5;
X1.val = 20;
X1.y = "twenty";
X2.val = 10;
X2.y = "ten";
X3.val = 50;
X3.y = "fifty";
X4.val = 5;
X4.y = "five";
X5.val = 0;
X5.y = "zero";
std::vector<Person> V;
V.push_back(X1);
V.push_back(X2);
V.push_back(X3);
V.push_back(X4);
V.push_back(X5);
std::priority_queue<Person,std::vector<Person>,Person> Q;
for (auto x: V) Q.push(x);
return 0;
}
Access Element from the Priority Queue We access the top element of the priority_queue using the top() method. In the above example, we have inserted elements into priority_queue in the following order: 1, 20, 7.
In computer science, a priority queue is an abstract data-type similar to a regular queue or stack data structure in which each element additionally has a priority associated with it. In a priority queue, an element with high priority is served before an element with low priority.
Priority queue ordered by second element (Min) The idea is to use the operator overloading to implement the priority queue ordered by its second element with the minimum element at the top.
The priority queue in C++ is a derived container in STL that considers only the highest priority element. The queue follows the FIFO policy while priority queue pops the elements based on the priority, i.e., the highest priority element is popped first.
For this usage, I'd suggest you use a combination of std::priority_queue
and an std::unordered_map
.
Let's restructure your data as follows:
struct PersonInfo {
std::string y;
};
This contains the mutable information about a person.
Now you have two containers:
an std::priority_queue<int>
of the values which were previously the val
s in your Person
class objects.
an std::unordered_map<int, PersonInfo>
mapping these values into PersonInfo
s.
For your stated intent
in which I have to check whether a particular object has been inserted into priority queue or not.
Simply check if things were inserted using the map; make sure to update it when pushing and popping the priority queue, though.
If it is being inserted, then I need to access that particular object and possibly update it.
Just use the unordered map.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With