模板参数列表中参数3的类型/值不匹配

时间:2018-06-07 06:20:57

标签: c++ priority-queue

我几乎成功实现了霍夫曼代码。我遇到错误,错误是这样的:

>>prog.cpp: In function 'int main()':
>>prog.cpp:49:57: error: type/value mismatch at argument 3 in template parameter list for 'template<class _Tp, class _Sequence, class _Compare> class std::priority_queue'

>>priority_queue<Node*,vector<Node*>,comparitor<Node*>> pq;
                                                         ^
>>prog.cpp:49:57: note: expected a type, got 'comparitor' Node*>

之前我曾尝试过指针,这是我第一次遇到这样的错误。

任何人都可以解释,为什么会出现这样的错误?这是我评论的代码:

#include <iostream>
using namespace std;
#include<queue>
class Node{
    public:
    int freq;
};
template<typename T>
bool comparitor(T a, T b)
{
    if(a->freq>b->freq)
    {return true;
    }
    else{
        return false;
    } // this is for the min heap
}

int main() {
        priority_queue<Node*,vector<Node*>,comparitor<Node*>> pq;// min heap please, comparitor is just for node and not a template, though I could have easily created that.
}

2 个答案:

答案 0 :(得分:2)

编译器错误几乎可以给你答案,第三个模板参数应该是一个类型,但你传递一个函数指针。

您需要将comparitor转换为仿函数:

template<typename T>
struct comparitor
{
  bool operator()(T a, T b)
  {
    if(a->freq>b->freq)
    {return true;
    }
    else{
        return false;
    } // this is for the min heap
  }
};

答案 1 :(得分:2)

std::priority_queue,需要三个参数 - 都是类型。你传递的是一个功能。将comparitor更改为具有operator()功能的课程。

// There is no reason to make it a class template. This is specifically
// designed to work only with Node*
struct comparitor
{
    bool operator()(const Node* a, const Node* b) const
    {
       return (a->freq > b->freq);
    }
};

并将其用作:

priority_queue<Node*, vector<Node*>, comparitor> pq;
相关问题