C++中vector,set,map自定义排序

一、vector排序

vector支持cmp,就类似数组,可以直接sort。

 1 #include <iostream>
 2 #include <algorithm>
 3 #include <string>
 4 #include <string.h>
 5 #include <math.h>
 6 #include <map>
 7 #include <queue>
 8 #include <stack>
 9 #include <set> 
10 typedef long long ll;
11 using namespace std;
12 bool cmp(int a, int b) {
13     return a > b;
14 }
15 int main()
16 {
17     cout << "VECTOR" << endl;
18     vector<int> v;
19     v.push_back(1); 
20     v.push_back(2); 
21     v.push_back(3); 
22     v.push_back(4);
23     sort(v.begin(), v.end(), cmp);
24     for(vector<int>::iterator it = v.begin(); it != v.end(); it++) {
25         cout << *it << endl;
26     } 
27 }

二、set排序,不可以使用sort,可以直接定义的时候就设置优先级

 1 #include <iostream>
 2 #include <algorithm>
 3 #include <string>
 4 #include <string.h>
 5 #include <math.h>
 6 #include <map>
 7 #include <queue>
 8 #include <stack>
 9 #include <set> 
10 typedef long long ll;
11 using namespace std;
12 bool cmp(int a, int b) {
13     return a > b;
14 }
15 int main()
16 {
17     set<int, greater<int> > s;
18     s.insert(1);
19     s.insert(2);
20     s.insert(3);
21     s.insert(4);
22     cout << "SET" << endl; 
23     for(set<int>::iterator it = s.begin(); it != s.end(); it++) {
24         cout << *it << endl;
25     }
26     
27 }

三、map自定义排序,也不能用sort,目前我只了解根据key排序,按照value还有待学习

 1 #include <iostream>
 2 #include <algorithm>
 3 #include <string>
 4 #include <string.h>
 5 #include <math.h>
 6 #include <map>
 7 #include <queue>
 8 #include <stack>
 9 #include <set> 
10 typedef long long ll;
11 using namespace std;
12 bool cmp(int a, int b) {
13     return a > b;
14 }
15 int main()
16 {
17     cout << "MAP" << endl; 
18     map<char, int, greater<char> > m;
19     m['c'] = 1;
20     m['b'] = 2;
21     m['a'] = 3;
22     for(map<char, int>::iterator it = m.begin(); it != m.end(); it++) {
23         cout << it->first << " " << it->second << endl;
24     }
25     
26 }

猜你喜欢

转载自www.cnblogs.com/wzy-blogs/p/9349323.html