std::priority_queue 和 std::pair<int, int>

std::priority_queue with std::pair<int, int>

您好,我有以下代码:

#include <algorithm>
#include <queue>
#include <functional>
std::priority_queue < std::pair<int, int>, std::greater<std::pair<int, int> > > q;

我正在尝试使用最小堆功能。 我已经搜索了几个小时,现在仍然无法得到明确的答案。 我见过很多人编写自定义比较函数,但我认为这是非常标准的操作。如果我取出 std::greater 函数,一切都会按预期工作,但它会创建一个最大堆。

编译时出现 14 个错误。

Error   C2039   'value_type': is not a member of 'std::greater<std::pair<int,int>>' 
Error   C2146   syntax error: missing '>' before identifier 'value_type'    
Error   C2039   'value_type': is not a member of 'std::greater<std::pair<int,int>>' 
Error   C3646   'value_type': unknown override specifier    
Error   C4430   missing type specifier - int assumed. Note: C++ does not support default-int    
Error   C2039   'size_type': is not a member of 'std::greater<std::pair<int,int>>'  
Error   C3646   'size_type': unknown override specifier     
Error   C4430   missing type specifier - int assumed. Note: C++ does not support default-int    
Error   C2039   'reference': is not a member of 'std::greater<std::pair<int,int>>'  
Error   C3646   'reference': unknown override specifier
Error   C4430   missing type specifier - int assumed. Note: C++ does not support default-int    
Error   C2039   'const_reference': is not a member of 'std::greater<std::pair<int,int>>'    
Error   C3646   'const_reference': unknown override specifier   
Error   C4430   missing type specifier - int assumed. Note: C++ does not support default-int

priority_queue 的第二个模板参数是要使用的基础容器类型,而不是要使用的比较运算符。它默认为 std::vector<T>,您可以明确指定:

typedef std::pair<int, int> QueueItem;
std::priority_queue <QueueItem, std::vector<QueueItem>, std::greater<QueueItem> > q;