
正文
C++中vector,set,map自定义排序
提示:扫一扫查出行【扫一扫了解最新限行尾号】
复制提示
一、vector排序
vector支持cmp,就类似数组,可以直接sort。
#include <iostream>
#include <algorithm>
#include <string>
#include <string.h>
#include <math.h>
#include <map>
#include <queue>
#include <stack>
#include <set>
typedef long long ll;
using namespace std;
bool cmp(int a, int b) {
return a > b;
}
int main()
{
cout << "VECTOR" << endl;
vector<int> v;
v.push_back();
v.push_back();
v.push_back();
v.push_back();
sort(v.begin(), v.end(), cmp);
for(vector<int>::iterator it = v.begin(); it != v.end(); it++) {
cout << *it << endl;
}
}
二、set排序,不可以使用sort,可以直接定义的时候就设置优先级
#include <iostream>
#include <algorithm>
#include <string>
#include <string.h>
#include <math.h>
#include <map>
#include <queue>
#include <stack>
#include <set>
typedef long long ll;
using namespace std;
bool cmp(int a, int b) {
return a > b;
}
int main()
{
set<int, greater<int> > s;
s.insert();
s.insert();
s.insert();
s.insert();
cout << "SET" << endl;
for(set<int>::iterator it = s.begin(); it != s.end(); it++) {
cout << *it << endl;
} }
三、map自定义排序,也不能用sort,目前我只了解根据key排序,按照value还有待学习
#include <iostream>
#include <algorithm>
#include <string>
#include <string.h>
#include <math.h>
#include <map>
#include <queue>
#include <stack>
#include <set>
typedef long long ll;
using namespace std;
bool cmp(int a, int b) {
return a > b;
}
int main()
{
cout << "MAP" << endl;
map<char, int, greater<char> > m;
m['c'] = ;
m['b'] = ;
m['a'] = ;
for(map<char, int>::iterator it = m.begin(); it != m.end(); it++) {
cout << it->first << " " << it->second << endl;
} }







