gpt4 book ai didi

c++ - 解释一下默认的priority_queue::top()的行为?

转载 作者:行者123 更新时间:2023-12-02 18:56:02 25 4
gpt4 key购买 nike

std::priority_queue ,默认情况下使用 std::vector<int>std::less比较器。默认情况下,priority_queue 是最大堆。

docs for top()状态:

The top element is the element that compares higher in the priority_queue, and the next that is removed from the container when priority_queue::top is called.

This member function effectively calls member front of the underlying container object.

因此默认构造 priority_queue像这样构造的整数:

auto maxheap = priority_queue<int>();
maxHeap.push(1);
maxHeap.push(3);
cout << maxHeap.top(); // outputs 3

但是,回到 top() 的描述,文档指出,实际上,成员 front在底层容器对象上被调用。如果我创建一个 vector 并使用 std::less 进行排序模仿 maxHeap 的底层容器:

auto vec = vector<int>{3, 1};
sort(vec.begin(), vec.end(), less<int>()); // {1, 3}
cout << vec.front(); // outputs 1

因为std::less按升序排序,调用 vec.front()最终返回最小值。

我对 priority_queue::top() 的默认行为的理解存在一些脱节以及文档所说的。有人可以向我解释一下吗?

最佳答案

您使用了错误的算法,您可以阅读https://en.cppreference.com/w/cpp/container/priority_queue/priority_queuestd::priority_queue 不使用 std::sort,而是使用 std::make_heap

如果您也在示例中使用它,您将得到您期望的输出。

std::vector<int> queue{1, 3};
std::make_heap(queue.begin(), queue.end(), std::less<>{});
std::cout << queue.front() << '\n';

Output: 3

关于c++ - 解释一下默认的priority_queue::top()的行为?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66183106/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com