• map 与仿函数的使用


    #include <iostream>
    #include <string>
    #include <map>
    using namespace std;
    
    
    //自己手写的仿函数
    class MyCompare
    {
    
    public:
    bool operator()(string s1, string s2) const // 注意此处一定要加上 const  在VS2022中,否则会报错 :  有类型“const MyCompare”的表达式会丢失一些 const - volatile 限定符以调用“bool MyCompare::operator ()(std::string, std:
    {
    return s1 > s2;
    }
    
    };
    
     
    
    void printMap(map<string, int, MyCompare>& m)
    {
    for (map<string, int> ::iterator it = m.begin(); it != m.end(); it++)
    {
    cout << "Key= " << it->first << " ,Value= " << it->second << endl;
    }
    }
    
    void test01()
    {
    // map容器的构造
    map<string, int, MyCompare> m;
    
    // map容器默认排序
    m.insert(make_pair("Tom", 18));
    m.insert(make_pair("Anthony", 23));
    m.insert(make_pair("Bob", 24));
    m.insert(make_pair("Sunny", 19));
    printMap(m);
    
    }
    
    int main()
    {
    test01();
    
    system("pause");
    return 0;
    }

     用标准库定义的仿函数:

    // Study01.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
    //
    
    #include <iostream>
    #include <string>
    #include <map>
    #include <functional>
    using namespace std;
    
    
    void printMap(map<string, int, greater<string>>& m)
    {
        for (map<string, int, greater<string>> ::iterator it = m.begin(); it != m.end(); it++)
        {
            cout << "Key= " << it->first << " ,Value= " << it->second << endl;
        }
    }
    
    void test01()
    {
        // map容器的构造
        map<string, int, greater<string>> m;
    
        // map容器默认排序
        m.insert(make_pair("Tom", 18));
        m.insert(make_pair("Anthony", 23));
        m.insert(make_pair("Bob", 24));
        m.insert(make_pair("Sunny", 19));
        printMap(m);
    }
    
    int main()
    {
        test01();
    
        system("pause");
        return 0;
    }
  • 相关阅读:
    bzoj1202 狡猾的商人
    bzoj1059 矩阵游戏
    bzoj1003 物流运输
    bzoj1601 灌水
    2017-10-25模拟赛
    洛谷—— P1051 谁拿了最多奖学金
    BZOJ——1611: [Usaco2008 Feb]Meteor Shower流星雨
    2017-10-23学大伟业Day1
    BZOJ——1610: [Usaco2008 Feb]Line连线游戏
    Vijos 包裹快递(二分)
  • 原文地址:https://www.cnblogs.com/huaan011/p/16064155.html
Copyright © 2020-2023  润新知