How to use STL priority_queue + comparator with a specific constructor?

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 initialize this queue by providing Comparator with the required reference in the constructor?

+5
source share
2 answers

You can provide an instance of Comparator to create it; otherwise Comparator() will be used as the default argument for the std::priority_queue constructor , but Comparator does not have a default constructor. eg.

 SomeObject so; std::priority_queue<std::string, std::set<std::string>, Comparator> queue(Comparator(so)); 

BTW: std::set does not satisfy the requirements of the base container std::priority_queue . Instead, you can use std::vector or std::deque .

The type of base container that will be used to store items. the container must satisfy the requirements of the SequenceContainer and its iterators must satisfy the requirements of RandomAccessIterator . In addition, it should provide the following functions with ordinary Semantics:

  • front ()
  • push_back ()
  • pop_back ()

The standard std :: vector and std :: deque containers satisfy these requirements.

+4
source

This has nothing to do with your Comparator , and anything related to std::set that does not meet the requirements of the SequenceContainer , you can use vector or deque or write your own SequenceContainer , making sure front , push_back and pop_back , and iterator implemented, which are RandomAccessIterator

+1
source

Source: https://habr.com/ru/post/1274153/


All Articles