自学内容网 自学内容网

STL优先队列比较器

有两个比较器,在std里面,一个是greater,一个是less,他们都有一个可以指定的模板类型。

#include <bits/stdc++.h>
using namespace std;
struct node {
    bool operator ()(const string& a, const string& b){
        return a<b;
    }
};
priority_queue<string, vector<string>, greater<string>>  pq;//第二个模板参数意思是使用vector<string>来作为优先队列存储!
void fun (){

    pq.emplace("abc");
    pq.emplace("das ");
    pq.emplace("23");
    pq.emplace("sada ");
    pq.emplace("fghdf ");
    while(!pq.empty()){
        cout<<pq.top()<<endl;
        pq.pop();
    }

}
int main(){
    fun ();

}

从小到大
在这里插入图片描述
从大到小
在这里插入图片描述
插一嘴,这里我们举例子是拿字符串举例子的,如果我们拿int类型举例子,这里就是greater <int>或者是less <int >

如果我们是自定义比较器:,如果想从小到大或者从大到小改就是修改return a>b;里面的大于小于号就可以啦!
在这里插入图片描述


原文地址:https://blog.csdn.net/weixin_46028606/article/details/137525597

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!