C++ 在优先队列内配对
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12685787/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Pair inside priority queue
提问by g4ur4v
I am trying to store pairs in priority queue and I am using a compare function that compares second value of each pair.
我正在尝试将对存储在优先级队列中,并且我正在使用一个比较函数来比较每对的第二个值。
#include<iostream>
#include<queue>
#include<utility>
using namespace std;
class CompareDist
{
public:
bool operator()(pair<int,int> n1,pair<int,int> n2) {
return n1.second>n2.second;
}
};
int main()
{
priority_queue<pair<int,int>,CompareDist> pq;
}
When I compile this I get an error
当我编译这个时,我收到一个错误
error: no type named ‘value_type' in ‘class CompareDist'
What could be the reason.I am new to STL.
可能是什么原因。我是 STL 的新手。
回答by Jesse Good
This is what priority_queuelooks like:
这是priority_queue 的样子:
template<
class T,
class Container = std::vector<T>,
class Compare = std::less<typename Container::value_type>
> class priority_queue;
In other words, CompareDist
should be the thirdargument and the second argument should be the container (which has value_type
), like the following:
换句话说,CompareDist
应该是第三个参数,第二个参数应该是容器(有value_type
),如下所示:
priority_queue<pair<int,int>,vector<pair<int,int>>,CompareDist> pq;
Notice also, that priority_queue
is what is called a "container adaptor". Another container is used as the underlying container and the priority_queue has special members functions for accessing it. Another example of a container adaptor would be std::stack.
另请注意,这priority_queue
就是所谓的“容器适配器”。另一个容器用作底层容器,并且priority_queue 具有用于访问它的特殊成员函数。容器适配器的另一个示例是 std::stack。
回答by RAMENDRA SINGH
priority_queue<pair<int,int>,vector<pair<int,int>>,CompareDist> pq;
you need to provide second argument for the inbuilt template of priority_queue.
您需要为priority_queue 的内置模板提供第二个参数。