欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 教育 > 培训 > C++ STL priority_queue 用法

C++ STL priority_queue 用法

2025/12/7 8:20:44 来源:https://blog.csdn.net/zg260/article/details/141299180  浏览:    关键词:C++ STL priority_queue 用法

一:功能

        用于创建优先级队列

二:用法

#include <iostream>
#include <vector>
#include <queue>
#include <ranges>auto topk_queue(std::input_iterator auto begin, std::sentinel_for<decltype(begin)> auto end, size_t k) {using vtype = std::iter_value_t<decltype(begin)>;using arrtype = std::vector<vtype>;std::priority_queue<vtype, arrtype, std::greater<vtype>> pq;while (begin != end) {pq.push(*begin);if (pq.size() > k)pq.pop();++begin;}arrtype result(k);for (auto &el: result | std::views::reverse) {el = std::move(pq.top());pq.pop();}return result;    
}int main() {std::vector<int> data{9, 2, 5, 3, 4, 2, 2, 1, 8};std::vector<int> out1 = topk_queue(data.begin(), data.end(), 2);for (auto v : out1)std::cout << v << " ";std::cout << "\n";std::vector<int> out2 = topk_queue(data.begin(), data.end(), 5);for (auto v : out2)std::cout << v << " ";std::cout << "\n";}

        

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词