Writing a custom comparator for a C++ map which has a custom defined key(为具有自定义键的C++映射编写自定义比较器)
本文介绍了为具有自定义键的C++映射编写自定义比较器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试为具有自定义键的C++映射编写自定义比较器。
struct key { int year; int no; };
map<key, detail, compare> details_map;
如果year
值相等,则它必须比较no
值。
我正在尝试找出一种方法来编写可以比较这两个值的比较器。到目前为止,我只能编写一个比较一个值的比较器。
struct Compare{bool operator()(const key &lhs,const key &rhs)const{return lhs.year<rhs.year;}}
谁能解释一下map
中比较器的工作原理吗?
另外,是否可以将比较器编写为函数?
推荐答案
在您的operator()
中,如果year
值相等,只需比较no
值:
struct Compare {
bool operator()(const key &lhs, const key &rhs) const {
if (lhs.year == rhs.year) {
return lhs.no < rhs.no;
}
return lhs.year < rhs.year;
}
};
是的,比较器可以作为独立函数实现:
bool Compare (const key &lhs, const key &rhs) {
if (lhs.year == rhs.year) {
return lhs.no < rhs.no;
}
return lhs.year < rhs.year;
}
或者,您可以让您的比较器使用std::tie()
来比较您的关键字字段。请参阅@Jarod42's answer。
但是,为您的key
类型实现operator<
会更有意义:
struct key {
int year;
int no;
bool operator<(const key &rhs) const {
if (year == rhs.year) {
return no < rhs.no;
}
return year < rhs.year;
}
};
或
struct key {
int year;
int no;
};
bool operator<(const key &lhs, const key &rhs) {
if (lhs.year == rhs.year) {
return lhs.no < rhs.no;
}
return lhs.year < rhs.year;
}
那么您不需要单独的比较器:
map<key, detail> details_map;
这篇关于为具有自定义键的C++映射编写自定义比较器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
织梦狗教程
本文标题为:为具有自定义键的C++映射编写自定义比较器


基础教程推荐
猜你喜欢
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 初始化列表*参数*评估顺序 2021-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- CString 到 char* 2021-01-01