本文介绍了std :: priority_queue的模板参数是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在浏览一些STL文档.我看到以降序存储的优先级队列的语法为:

I was looking through some STL documentation. I see that the syntax for a priority queue which stores in a descending order is:

std::priority_queue<int> q ;
//gives 9 8 7 6 5 4 3 2 1  when pushed and obtained

但是,为了以递增方式存储,它是:

However, for storing in an ascending fashion, it's:

std::priority_queue< int, std::vector<int>, std::greater<int> > q ;
//gives 1 2 3 4 5 6 7 8 9 when pushed and obtained

我想知道第二个示例中额外模板参数的具体用途是什么.就像在该示例中, std :: vector< int> 做什么?

I want to know what are the specific uses of the extra template parameters in the second example. As in, what does std::vector<int> do in that example?

还可以有人进一步解释这个声明吗?

Also, can someone could further explain this declaration?

priority_queue< pair<int ,int > , vector< pair<int ,int > > , greater< pair<int ,int > > > q ;

推荐答案

std:: priority_queue 本身不是容器,而是一个容器适配器,这意味着它在内部使用另一个容器将实际数据存储在队列中.

std::priority_queue is not a container in itself, it's a container adaptor, which means it uses another container internally to store the actual data in the queue.

默认情况下,它使用存储在队列中的类型的 std :: vector .

By default it uses a std::vector of the type stored in the queue.

这里的问题是,就像将参数传递给具有默认参数的函数一样,即使它们具有默认类型,也不能跳过模板列表中的参数,必须始终提供先前的模板参数.

The problem here is that just like passing arguments to a function with default arguments, you can't skip arguments in the template list even if they have default types, you must always provide the previous template arguments.

如果看到链接的引用,您将看到 std :: priority_queue 的第二个和第三个模板参数具有默认类型.如果要更改第三个模板参数,则还必须提供第二个模板参数,这是实际的基础容器.因此,对于 int std :: priority_queue ,您需要提供 std :: vector< int> .

If you see the linked reference you will see that the second and third template arguments to std::priority_queue have default types. If you want to change the third template argument you must also provide the second template argument as well, which is the actual underlying container. So for a std::priority_queue of int, you need to provide std::vector<int>.

但是,有一种方法可以不将比较器的类型作为模板参数传递,即 std :: priority_queue 构造函数还为比较器函数采用(可选)参数.在这里,您可以提供任何函数,函数对象,lambda或其他可调用对象.

The above declaration creates a std::greater<int> object and passes it as comparator to the std::priority_queue constructor.

这篇关于std :: priority_queue的模板参数是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-23 18:30