c++ - std::priority_queue 与 std::pair<int, int>

标签 c++ c++11 priority-queue std-pair

您好,我有以下代码:

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

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

编译时出现 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;

关于c++ - std::priority_queue 与 std::pair<int, int>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42100055/

相关文章:

c++ - 未知类型名称类

c++ - 陷入 std::function 和成员函数指针的困惑:(

c++ - 创建节点并计算汽车的初始位置

c++ - 未在范围内声明 - priority_queue C++ 的友元比较器类

c++ - 删除#pragma once 警告

c++ - 忽略虚假唤醒,condition_variable::wait_for

unit-testing - 如何编写 static_assert 的可运行测试?

c++ - 括号后面的类名是什么类型

c++ - 优先队列堆化

node.js - Bull 队列尚未完成