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 }
  • 相关阅读:
    windows10 中 svn 代码统计工具 StatSVN 使用详解
    Windows 10 安装 JDK14 Java 环境,没有 jre 包
    GET和POST两种基本请求方法的区别
    图解HTTP学习笔记(一)WEB基础
    【LinuxShell】cp 用法详解
    博客陆续迁移中...
    显示git忽略文件
    字符串遍历
    SDWebImage源码分析(二)
    其他
  • 原文地址:https://www.cnblogs.com/wzy-blogs/p/9349323.html
Copyright © 2011-2022 走看看