在我们用map进行插入数据时,需要对自定义key值进行<运算符重载,具体可参考
c++11 map自定义key_c++ map自定义key_小立爱学习的博客-CSDN博客
代码如下,<运算符进行重载后,貌似没有问题
#include <iostream>
#include <map>
using namespace std;
struct DateTime
{
int year;
int month;
bool operator < (const DateTime& time) const
{
if (year < time.year)
{
return true;
}
if (month < time.month)
{
return true;
}
return false;
}
};
int main()
{
map<DateTime, int> dateMap;
DateTime a, b, c;
a.year = 2001;
a.month = 2;
b.year = 2003;
b.month = 3;
c.year = 1990;
c.month = 3;
dateMap.insert(std::pair<DateTime, int>(a, 1));
dateMap.insert(std::pair<DateTime, int>(b, 1));
dateMap.insert(std::pair<DateTime, int>(c, 1));
return 0;
}
但是我们一运行,确会出现invalid comparator错误,这是因为它并没有遵循C++中的严格弱序规则
当大量数据进行排序,若无严格排序规则会引起数据顺序的混乱
处理这个问题很简单,我们只需要检查重载<是否遵守严格弱序原则即可 ,将代码修改为
bool operator < (const DateTime& time) const
{
if (year != time.year)
{
return year < time.year;
}
if (month != time.month)
{
return month < time.month;
}
return false;
}
严格弱序原则可参考boost文档
参考文章:
C++: “invalid comparator” 断言 - IT工具网
std::map 自定义key类型,重写operator<() 没有严格弱序引起的“invalid comparator”_Lay_Nobody的博客-CSDN博客