zoukankan      html  css  js  c++  java
  • (C++)Set集合,比较函数

    Set的默认将里面的元素从小到大排序。

    如果想从大到小,需要用到greater<typename>

    如果Set里的元素是string类型的,则是按字典序排序的。

    比如:下面这段代码是按字典序从大到小排列的。

    #include<stdio.h>
    #include<stdlib.h>
    #include<unordered_map>
    #include<iostream>
    #include<string>
    #include<assert.h>
    #include<set>
    int main() {
        string MainWord = "abppplee";
        set<string, greater<string>> WordPool;
        WordPool.insert("able");
        WordPool.insert("ale");
        WordPool.insert("apple");
        WordPool.insert("bale");
        WordPool.insert("kangaroo");
        //cout << find(MainWord, WordPool) << endl;
        set<string, greater<int>>::iterator it;
        for (it = WordPool.begin(); it != WordPool.end(); it++)
            cout << (*it) << endl;
        return 0;
    }

    也可以自己写个结构体来重载比较函数:

    #include<stdlib.h>
    #include<unordered_map>
    #include<iostream>
    #include<string>
    #include<assert.h>
    #include<set>
    struct length_more {
        bool operator()(const string& s1, const string& s2) {
            return s1.size() > s2.size();
        }
    };
    int main() {
        string MainWord = "abppplee";
        set<string, length_more> WordPool;
        WordPool.insert("able");
        WordPool.insert("ale");
        WordPool.insert("apple");
        WordPool.insert("bale");
        WordPool.insert("kangaroo");
        //cout << find(MainWord, WordPool) << endl;
        set<string>::iterator it;
        for (it = WordPool.begin(); it != WordPool.end(); it++)
            cout << (*it) << endl;
        return 0;
    }
  • 相关阅读:
    简单字典操作
    字符串操作
    2017年10月7日
    循环列表练习
    Zabbix4.0系统告警"Zabbix agent on Zabbix server is unreachable for 5 minutes"
    Zabbix4.0系统告警“Zabbix server is not running”
    FreeRADIUS使用了在Cisco IOS配置示例的管理访问
    Cisco AAA Configuration
    使用工具Csvde导出域中所有用户信息
    McAfee Agent卸载方法
  • 原文地址:https://www.cnblogs.com/Bella2017/p/11153415.html
Copyright © 2011-2022 走看看