0

I have numbers from 1 to n, and an array of priorities P of size n. I want to declare a priority queue using P as their priorities.

I don't want to define a new type of object that contains the number and its priority, I want to use a priority queue of int objects and pass a custom comparison object that depends on P to std::priority_queue. I tried the following but it doesn't work:

std::priority_queue<int, vector<int>, [P](int i, int j){ return P[i]<P[j]; }> PQ;

I also tried defining a class with a bool operator(int i, int j) {P[i] < P[j]} member and a constructor where I can pass P to it but that also didn't work.

How should I declare my priority queue?


The following seems to work:

class MyLess{
 public:
  MyLess(const int* p) {p_ = p;}
  bool operator()(const int &lhs, const int &rhs) const { return p_[lhs] < p_[rhs]; }

 private:
  const int* p_;
};
...
std::priority_queue<int, vector<int>, MyLess> PQ(P);
1
  • 1
    How exactly did not it work? Commented Jul 31, 2015 at 10:03

1 Answer 1

2

Option #1

#include <functional>
// ...
std::priority_queue<int
                  , std::vector<int>
                  , std::function<bool(int,int)>
                  >
                  PQ([P] (int i, int j) { return P[i] < P[j]; });

Option #2

auto cmp = [P] (int i, int j) { return P[i] < P[j]; };

std::priority_queue<int, std::vector<int>, decltype(cmp)> PQ(cmp);
Sign up to request clarification or add additional context in comments.

4 Comments

The first one gives the following error similar to what I was getting: "no matching function for call to 'std::priority_queue<int, std::vector<int>, std::function<bool(int, int)> >::priority_queue(methodname::__lambda0)' PQ([T] (int i, int j) { return T[i] < T[j]; });"
@Kaveh and the compiler you use is... ?
gcc-4.8.1. The second one causes internal compiler error (gcc-4.8.1): 0x4ea72c check_initializer ../../../work/gcc-4.8.1/gcc/cp/decl.c:5590 0x4edab2 cp_finish_decl(tree_node*, tree_node*, bool, tree_node*, int) ../../../work/gcc-4.8.1/gcc/cp/decl.c:6347 ...
@Kaveh demo1, demo2

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.