首页 > 解决方案 > std::map 如何在 C++ 中使用自定义比较函数(或调用频率)?

问题描述

我试图为字典排序编写一些代码,并遇到了这个示例代码:

#include <cstring>
#include <fstream>
#include <functional>
#include <iostream>
#include <map>
#include <vector>

using std::string;
using std::transform;
using std::map;
using std::cout;

struct Compare {
    bool operator() (const int& s0, const int& s1) const {
        cout << "in compare: s0=" << s0 << " s1=" << s1 << "\n";

        return s0 < s1;
    }
};

typedef map<int, int, Compare> num_count;

int main(){
   num_count nc;
   auto nums = { 4, 2, 5, 1, 6 };

    for (auto num : nums) {
        cout << "num=>" << num << '\n';
        nc[num]++;
    }

    for(auto elem : nc)
        cout << elem.first << '\n';

    return 0;
}

魔杖盒的链接

该代码几乎可以按照我希望的方式工作。我只是想了解比较功能。在第一次插入时,没有比较是一个(显然)。在第二次插入时,比较函数被调用了 3 次。这是我不明白的部分。我最接近理解的是,这是由于地图的实现方式(红黑树)。给出一些解释的链接之一是此处的评论。

有人可以详细解释一下吗?谢谢。

标签: c++11

解决方案


推荐阅读