[英]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 它提供 STL priority_queue 逻辑来比较元素。
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.正如您所看到的,为了让这个比较逻辑正常工作,我需要为这个 class 提供一个 2D 向量。
so, I modified the class as -所以,我将 class 修改为 -
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.我将该二维数组放入 function 中,我还需要在其中初始化 priority_queue。
code for that function -该代码 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.现在的问题是我不知道如何为我的比较逻辑提供所需的二维数组“vec”。
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;
//
}
};
As awesoon pointed out, you have to pass an instantiation of you Comp class to the constructor of std::priority_queue.正如 awesoon 指出的那样,您必须将 Comp class 的实例化传递给 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 ).但是您必须使用大括号而不是括号以避免与 function 声明的歧义(cmp. 构造函数未返回可用的 object )。
Your example with added constructor call: https://godbolt.org/z/18b4KT66v您添加了构造函数调用的示例: https://godbolt.org/z/18b4KT66v
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.