一:功能
用于创建优先级队列
二:用法
#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";}
