【问题标题】:C++ priority queue with custom compare function in a class类中具有自定义比较功能的 C++ 优先级队列
【发布时间】:2016-02-22 04:11:24
【问题描述】:

我正在尝试使用自定义比较函数创建优先级队列,作为类的数据成员。如果我将队列放在一个类中,则代码无法编译,但是如果它在 main 函数中,则它可以正常工作:

#include <queue>
#include <vector>
using namespace std;

bool cmp(int x, int y) { return (x > y); }

class A {
public:
private:
    priority_queue<int, vector<int>, decltype(cmp) > pq(cmp); // Error at pq(cmp) : function "cmp" is not a type name
};


int main() {

    priority_queue<int, vector<int>, decltype(cmp) > pq(cmp); // no error here
    return 0;
}

我在上面的代码中使用 Microsoft VS2015。我是否将cmp 函数放在类中没有区别。您能否解释一下为什么会发生这种情况以及可能的解决方案?

编辑 1:

main中的这一行

priority_queue<int, vector<int>, decltype(cmp) > pq(cmp); // no error here

确实会产生错误,但我的 IDE 无法检测到它。使用decltype(&amp;cmp) 将消除此错误。

【问题讨论】:

  • decltype(&amp;cmp) 工作了吗? (注意添加的运营商地址)
  • @DanielJour 它仍然只适用于main 函数,而不是类。

标签: c++ priority-queue


【解决方案1】:

首先我在考虑你的编译器中的一个错误,但我could reproduce 它。然后突然变得很明显:

foo bar(baz);

如果您仔细观察,这与您的代码中的模式相同。由于最麻烦的解析,这是一个函数声明

因此,您尝试在这里声明一个名为 pq 的函数,返回一个优先级队列并具有一个 cmp 类型的参数。但是,编译器无法找到该类型。

改用大括号初始化应该可以解决这个问题:

#include <queue>
#include <vector>
using namespace std;

bool cmp(int x, int y) { return (x > y); }

class A {
public:
private:
    priority_queue<int, vector<int>, decltype(&cmp) > pq{cmp};
};


int main() {
   // priority_queue<int, vector<int>, decltype(cmp) > pq(cmp); // this is wrong, too
    return 0;
}

(Ideone)

不过,请不要问我为什么它在函数内部工作。它也不在函数内部工作。

【讨论】:

  • 非常感谢,这个答案很有帮助。代码现在可以正常工作了。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-04-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多