STL优先级队列非类型编译错误

时间:2012-11-18 04:34:43

标签: c++ stl priority-queue

我以为我弄清楚了,但我想我错了。我的印象是'< ...>'中的第一个元素是要存储在队列中的类型,第二个是容器类型(选项是'vector'或'dequeue'),第三个是重载'()'运算符以进行比较的类。基于此,我认为以下代码应该编译,但它不会:(

std::priority_queue<uint32_t*, std::vector<uint32_t*>, edgeComparator> q();

uint32_t* nodeEdge = new uint32_t[2];
nodeEdge[0] = startN;
nodeEdge[1] = 0;

q.push(nodeEdge);

'edgeComparator'定义如下:

class edgeComparator
{
   public:
      bool operator() (const uint32_t*& lhs, const uint32_t*& rhs) const
      {
         return (lhs[1]>rhs[1]);
      }
};

这是我得到的错误:

./Graph.cpp: In member function `void Graph::findShortestPath()':
./Graph.cpp:148: error: request for member `push' in `q', which is of non-class type `std::priority_queue<uint32_t*, std::vector<uint32_t*, std::allocator<uint32_t*> >, edgeComparator> ()()'

更糟糕的是,我在尝试'q.empty()'

时也遇到了这个错误
./Graph.cpp:150: error: request for member `empty' in `q', which is of non-class type `std::priority_queue<uint32_t*, std::vector<uint32_t*, std::allocator<uint32_t*> >, edgeComparator> ()()'

1 个答案:

答案 0 :(得分:4)

你有:

std::priority_queue<uint32_t*, std::vector<uint32_t*>, edgeComparator> q();

但相反,你应该使用:

std::priority_queue<uint32_t*, std::vector<uint32_t*>, edgeComparator> q;

第一个版本声明一个名为q函数,它不带参数,并返回类型为std::priority_queue<...>的值。

第二个版本声明名为q变量,其类型为std::priority_queue<...>,默认初始化。