C++ priority

    xiaoxiao2021-03-25  129

    在使用优先队列的过程遇到了点小问题,解决后记录分享下~

    priority_queue容器构造时需要三个参数:

    数据类型保存数据的容器(必须是用数组实现的容器,比如vector,但不能用list。同时vector也是默认的实现容器元素比较方式(使用<操作符进行比较,表示大值优先)

      默认最大值优先出队,如果需要使用最小值的优先队列,可使用greater<>作为比较方式。

    自定义比较函数可参考http://en.cppreference.com/w/cpp/container/priority_queue中的例子,使用auto cmp =lambda表达式和decltype(cmp)作为第三个参数。这比网上很多资料说的重载运算符、自定义的仿函数要简单方便得多。

    例子代码如下(来源为上面的网址):

    #include <functional> #include <queue> #include <vector> #include <iostream> template<typename T> void print_queue(T& q) { while(!q.empty()) { std::cout << q.top() << " "; q.pop(); } std::cout << '\n'; } int main() { std::priority_queue<int> q; for(int n : {1,8,5,6,3,4,0,9,7,2}) q.push(n); print_queue(q); std::priority_queue<int, std::vector<int>, std::greater<int> > q2; for(int n : {1,8,5,6,3,4,0,9,7,2}) q2.push(n); print_queue(q2); // Using lambda to compare elements. auto cmp = [](int left, int right) { return (left ^ 1) < (right ^ 1);}; std::priority_queue<int, std::vector<int>, decltype(cmp)> q3(cmp); for(int n : {1,8,5,6,3,4,0,9,7,2}) q3.push(n); print_queue(q3); }

    Output: 9 8 7 6 5 4 3 2 1 0 0 1 2 3 4 5 6 7 8 9 8 9 6 7 4 5 2 3 0 1

    转载请注明原文地址: https://ju.6miu.com/read-3510.html

    最新回复(0)