c++11 - 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 次。这是我不明白的部分。我最接近理解的是,这是由于地图的实现方式(红黑树)。给出一些解释的链接之一是此处的评论。
有人可以详细解释一下吗?谢谢。
解决方案
推荐阅读
- java - Spring Data JPA:如果 Id 存在,则使用 saveAll 时防止更新
- ios - SwiftUI:在未突出显示的 3 列中启动时预选 NavigationLink
- python - 为什么我的循环没有迭代列表中的第二个相同的值?
- python - 使用 datetime.time 类型重采样 pandas 索引
- php - 将数据插入 laravel 数据库
- python-3.x - 下边界既不是与src大小相同类型的数组,也不是函数中的标量
- c++ - 非图形 C/C++ 代码的 OpenGL 数据类型?
- django - 如何将我的投诉列表呈现到卡片中以便能够查看它们?
- libasound - Aplay 示例格式不可用
- amazon-web-services - 处于连接丢失状态的 Systems Manager 托管实例