一、首先明确map定义
map是STL的一个关联容器,它提供一对一的hash。
- 第一个可以称为关键字(key),每个关键字只能在map中出现一次;
- 第二个可能称为该关键字的值(value);
二、注意事项
如果定义的map的关键字(key)是标准库中的类型如(int)(double)(string)等等,则无需重载“<”;
如果定义的map的关键字(key)是自己定义的 结构/类 对象,则注意要重载“<”。
struct indices{ unsigned int v, vt; }
map<indices,int> indicesMap;
如下图:
struct indices
{
unsigned int v, vt;
bool operator<(const struct indices & right)const //重载<运算符
{
if (this->vt < right.vt)
return true;
else if (this->vt == right.vt)
{
if (this->v < right.v)
return true;
}
return false;
}
};
1.为什么?
因为map內部的实现自建一颗红黑树,这颗树具有对数据自动排序的功能。在map内部所有的数据都是有序的。比如一个班级中,每个学生的学号跟他的姓名就存在著一对一映射的关系。所以如果不对自定义对象重载“<”函数,会导致map无法完成自动排序,程序会报错:
2.怎么办?
逻辑很简单,只需要定义一个逻辑严密的" operator<"函数即可。
逻辑严密是指在自定义对象的任何情况下,都有唯一的大小比较结果。而且不会出现
a<b,b<c ,而c<a的情况。
代码如下:
struct indices
{
unsigned int v, vt;
bool operator<(const struct indices & right)const //重载<运算符
{
if (this->vt < right.vt)
return true;
else if (this->vt == right.vt)
{
if (this->v < right.v)
return true;
}
return false;
}
};