• 利用仿函数可以改变排序规则

    代码演示:

    1. #include<iostream>
    2. using namespace std;
    3. #include<map>
    4. //map容器排序
    5. class myCompare {
    6. public:
    7. bool operator()(int v1, int v2)const {
    8. //降序
    9. return v1 > v2;
    10. }
    11. };
    12. void test01() {
    13. //创建map容器
    14. map<int, int, myCompare>m;
    15. //默认按key值排序好
    16. m.insert(make_pair(1, 10));
    17. m.insert(make_pair(2, 20));
    18. m.insert(make_pair(3, 30));
    19. m.insert(make_pair(4, 40));
    20. m.insert(make_pair(5, 50));
    21. for (map<int, int>::iterator it = m.begin(); it != m.end(); it++) {
    22. cout << "key= " << (*it).first << " value= " << it->second << endl;
    23. }
    24. cout << endl;
    25. }
    26. int main() {
    27. test01();
    28. return 0;
    29. }

    运行结果:
    image.png