I want to do this:
#include <queue>
#include <set>
class Comparator
{
public:
Comparator(SomeObject& rTool) : mrTools(rTool) {}
bool operator()(const std::string& a, const std::string& b)
{
return mrTools.doSomething(a,b);
}
private:
SomeObject& mrTools;
}
std::priority_queue<std::string, std::set<std::string>, Comparator> queue;
//<- this doesn't compile
How can I initalize this queue providing Comparator with the reference it needs in the constructor ?
priority_queue is categorized as a STL container adaptor. It is like a queue that keeps its element in sorted order. Instead of a strict FIFO ordering, the element at the head of the queue at any given time is the one with the highest priority.
You may have often come to a situation when you need to use a priority queue, but your datatype is something else that can't be compared by default (using '<' operator what is used by default). In such cases, we need to declare our comparator function. We can use the lambda function for that.
In C++, an internal heap structure is implemented in the priority queue. By default, a max-heap is maintained in the priority queue, which means the highest priority element will be at the top of the priority queue. A min-heap can also be created by simply specifying the suitable Compare function object.
You can provide an instance of Comparator
to construct it; otherwise Comparator()
will be used as the default argument to constructor of std::priority_queue
, but Comparator
doesn't have a default constructor. e.g.
SomeObject so;
std::priority_queue<std::string, std::set<std::string>, Comparator> queue(Comparator(so));
BTW: std::set
doesn't satisfy the requirement of the underlying container of std::priority_queue
. You can use std::vector
or std::deque
instead.
The type of the underlying container to use to store the elements. The container must satisfy the requirements of SequenceContainer, and its iterators must satisfy the requirements of RandomAccessIterator. Additionally, it must provide the following functions with the usual semantics:
- front()
- push_back()
- pop_back()
The standard containers std::vector and std::deque satisfy these requirements.
This has nothing to do with your Comparator
, and everything to do with std::set
not satisfying the requirements of SequenceContainer
. You can use vector
or deque
, or write your own SequenceContainer
, making sure to implement front
, push_back
and pop_back
, and have iterator
s that are RandomAccessIterator
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