Reputation: 2251
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;
}
Upvotes: 7
Views: 8255
Reputation: 76297
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.
Upvotes: 1