[英]Type error in C++ when instantiating a priority_queue of int pairs with a custom comparator (to implement a min heap)
目前正在解决我需要最小堆对的 leetcode 问题。
我正在尝试将priority_queue
与int
pair
和自定义比较类型一起使用。
执行相同的尝试失败并出现以下错误:
在 prog_joined.cpp:1 中包含的文件中:在 /precompiled/headers.h:55 中包含的文件中:在 /usr/bin/../lib/gcc/x86_64-linux-gnu/9/.. 中包含的文件中/../../../include/c++/9/queue:64: /usr/bin/../lib/gcc/x86_64-linux-gnu/9/../../../。 ./include/c++/9/bits/stl_queue.h:467:7: error: static_assert 由于要求'is_same<int, std::pair<int, int>>::value' "value_type 必须相同而失败作为底层容器” static_assert(is_same<_Tp, typename _Sequence::value_type>::value, ^ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~~~~~ 第 9 行:字符 67:注意:在模板 class 'std::priority_queue<int, std::vector<std 的实例化中::pair<int, int>, std::allocator<std::pair<int, int>>>, std::greater>' 在此请求 priority_queue<int, vector<pair<int, int>>, Greater> pq;
这是我试图实现堆的代码:
#include <queue>
#include <utility>
using namespace std;
//...
priority_queue<int, pair<int, int>, greater<int>> pq;
正如您在std::priority_queue
文档中看到的:
pair<int,int>
)。 例如,如果您想要一个使用std::vector
作为容器的int
pair
的priority_queue
,您需要:
std::priority_queue<std::pair<int, int>, // data type
std::vector<std::pair<int,int>>, // container type
std::greater<std::pair<int,int>>> pq; // compare type
注意:正如您在此处看到的, std::greater
使用的比较运算符的std::pair
实现是:
通过 operator< 按字典顺序比较 lhs 和 rhs,即比较第一个元素,只有当它们相等时,才比较第二个元素。
如果这不是您需要的,您可以为std::pair<int,int>
实现自己的比较类型。
附注:最好避免using namespace std
。 见这里: 为什么“使用命名空间标准;” 被认为是不好的做法? .
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.