使用自定义比较器函数在 class 中定义优先级队列
Defining priority queue inside a class with a custom comparator function
我正在尝试使用自定义比较器定义优先级队列,如下所示:
typedef bool (*comp)(int,int);
bool compare(int exp1,int exp2){
return (exp1 > exp2);
}
class test{
public:
priority_queue<int,vector<int>,comp> test_pq(compare); // Gives compilation error
};
int main ()
{
priority_queue<int,vector<int>,comp> pq(compare); // Compiles perfectly
return 0;
}
这是出现的编译错误
test.cpp:18:47: error: ‘compare’ is not a type
priority_queue<int,vector<int>,comp> test_pq(compare);
^
我还尝试在测试中声明另一个比较函数 class 但没有效果。为什么 main 函数中的优先级队列可以编译,而 class 中的优先级队列不能编译?为比较器定义一个专用的 class 是唯一可行的方法吗?
谢谢。
您在 test
class 中的代码试图声明一个带有错误签名的方法 test_pq
。
要定义成员变量,您可以在初始化时使用大括号(需要 C++11):
class test{
public:
priority_queue<int,vector<int>,comp> test_pq{compare};
};
要在 C++11 之前实现相同的功能,您需要为 test
class:
编写自定义构造函数
class test
{
public:
test()
: test_pq(compare)
{
// Constructor code here
}
private:
priority_queue<int,vector<int>,comp> test_pq;
};
我正在尝试使用自定义比较器定义优先级队列,如下所示:
typedef bool (*comp)(int,int);
bool compare(int exp1,int exp2){
return (exp1 > exp2);
}
class test{
public:
priority_queue<int,vector<int>,comp> test_pq(compare); // Gives compilation error
};
int main ()
{
priority_queue<int,vector<int>,comp> pq(compare); // Compiles perfectly
return 0;
}
这是出现的编译错误
test.cpp:18:47: error: ‘compare’ is not a type
priority_queue<int,vector<int>,comp> test_pq(compare);
^
我还尝试在测试中声明另一个比较函数 class 但没有效果。为什么 main 函数中的优先级队列可以编译,而 class 中的优先级队列不能编译?为比较器定义一个专用的 class 是唯一可行的方法吗? 谢谢。
您在 test
class 中的代码试图声明一个带有错误签名的方法 test_pq
。
要定义成员变量,您可以在初始化时使用大括号(需要 C++11):
class test{
public:
priority_queue<int,vector<int>,comp> test_pq{compare};
};
要在 C++11 之前实现相同的功能,您需要为 test
class:
class test
{
public:
test()
: test_pq(compare)
{
// Constructor code here
}
private:
priority_queue<int,vector<int>,comp> test_pq;
};