zoukankan      html  css  js  c++  java
  • 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 }
  • 相关阅读:
    HNOI 2006 BZOJ 1195 最短母串
    BZOJ 3029 守卫者的挑战
    Codeforces 401D Roman and Numbers
    ZJOI2010 数字计数
    BZOJ 3329 Xorequ
    Codeforces 235 C
    SPOJ 8222 Substrings
    BZOJ 1396 识别子串
    (模板)归并排序
    poj3122 Pie (二分)
  • 原文地址:https://www.cnblogs.com/wzy-blogs/p/9349323.html
Copyright © 2011-2022 走看看