5

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 ?

2 Answers 2

6

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.

Sign up to request clarification or add additional context in comments.

1 Comment

A priority_queue has less functionality than a set anyway. The only (but possibly very good) reason to prefer priority_queue is efficiency.
1

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 iterators that are RandomAccessIterator

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.