samar taj Shaikh
samar taj Shaikh

Reputation: 1185

Not able to pass data to priority_queue in c++

This is my comparator class which provides STL priority_queue logic for comparing elements.

class Comp {
 public:
  bool operator() (pair<int, int>& a, pair<int, int>& b) {
    int val1 = vec[a.first][a.second];
    int val2 = vec[b.first][b.second];
    return val1 > val2;
  }
};

as you can see for this comparison logic to work properly I need to provide a 2D vector to this class.

so, I modified the class as -

class Comp {
  vector<vector<int>> vec;

 public:
  Comp(vector<vector<int>>& v): vec{v} {} 

  bool operator() (pair<int, int>& a, pair<int, int>& b) {
    int val1 = vec[a.first][a.second];
    int val2 = vec[b.first][b.second];
    return val1 > val2;
  }
};

and I am getting that 2D array into a function, in which I need to initialize the priority_queue as well.

code for that function -

class random {
public:
    vector<int> func(vector<vector<int>> vec, int k) {
        priority_queue<pair<int, int>, vector<pair<int, int>>, Comp> pq;
        //
    }
};

now the problem is I do not know how can I provide the required 2D array 'vec' to my comparison logic.

Does anyone know how to do that?

complete code -

class Comp {
    vector<vector<int>> vec;

public:
    Comp(vector<vector<int>>& v): vec{v} {} 

    bool operator() (pair<int, int>& a, pair<int, int>& b) {
        int val1 = vec[a.first][a.second];
        int val2 = vec[b.first][b.second];
        return val1 > val2;
    }
};

class random {
public:
    vector<int> func(vector<vector<int>> vec, int k) {
        priority_queue<pair<int, int>, vector<pair<int, int>>, Comp> pq;
        //
    }
};

Upvotes: 0

Views: 72

Answers (1)

Jens
Jens

Reputation: 83

As awesoon pointed out, you have to pass an instantiation of you Comp class to the constructor of std::priority_queue. But you have to use braces instead of parantheses to avoid ambiguity with a function declaration (cmp. Constructor not returning usable object).

Your example with added constructor call: https://godbolt.org/z/18b4KT66v

Upvotes: 1

Related Questions