按字符串长度升序,长度相同则按字典序
优先按字符串长度升序排序
如果长度相同,则按字典序升序排序
使用 set<string, cmp>
#include <bits/stdc++.h>
using namespace std;// 比较器
struct cmp{bool operator()(const string& a ,const string& b) const{if(a.size() == b.size())return a<b;return a.size() < b.size();}
};//记得 ;int main() {set<string,cmp> myset;myset.insert("apple");myset.insert("kiwi");myset.insert("pear");myset.insert("grape");myset.insert("banana");myset.insert("mango");for( auto & s : myset){cout << s << endl;}return 0;
}
输出:
kiwi
pear
apple
grape
mango
banana
#include <bits/stdc++.h>
using namespace std;int main() {priority_queue<string,vector<string>> pq;pq.push("apple");pq.push("kiwi");pq.push("pear");pq.push("grape");pq.push("banana");pq.push("mango");while(!pq.empty()){string str = pq.top();pq.pop();cout << str << endl;}return 0;
}
默认大根堆
内部按字典序建最大堆,pq.top()
永远是字典序最大的字符串。
输出:
pear
mango
kiwi
grape
banana
apple
按字符串长度排序的大根堆
字符串长度越长,优先级越高,pq.top()
会返回当前堆中最长的字符串。
当长度相同,它们会被当作“相等”处理,顺序不确定(非稳定)。
#include <bits/stdc++.h>
using namespace std;// 比较器
// 注意:priority_queue 比较器是 “谁优先级低” 返回 true
struct cmp{bool operator()(const string& a ,const string& b) const{// if(a.size() == b.size())// return a<b;return a.size() < b.size(); //长的字符串优先(更长 = 优先级更高)}
};
// 举例:若 a = "kiwi", b = "banana",则 a.size() < b.size() 返回 true,表示 kiwi 的优先级低int main() {// 定义一个优先队列,存放 string 类型// 使用 vector<string> 作为底层容器,cmp 为比较器priority_queue<string,vector<string> ,cmp > pq;pq.push("apple");pq.push("kiwi");pq.push("pear");pq.push("grape");pq.push("banana");pq.push("mango");while(!pq.empty()){string str = pq.top();pq.pop();cout << str << " ";}return 0;
}
最短的字符串先出来,长度相同则字典序小的先出来
#include <bits/stdc++.h>
using namespace std;// 比较器
struct cmp{bool operator()(const string& a ,const string& b) const{if(a.size() == b.size())return a > b; //如果两个字符串长度相等,按字典序升序排列(小的优先)return a.size() > b.size(); //按长度升序排列(短的优先)}
};int main() {priority_queue<string,vector<string> ,cmp > pq;pq.push("apple");pq.push("kiwi");pq.push("pear");pq.push("grape");pq.push("banana");pq.push("mango");while(!pq.empty()){string str = pq.top();pq.pop();cout << str << " ";}return 0;
}
输出:kiwi pear apple grape mango banana