最近在使用stl中的map容器时,碰到key为结构体的情况,总结如下,以便提醒自己。
我的使用情景是,我需要根据不同的比例尺、道路类型这两个参数获取到对应的道路宽度,由于我是使用map解决这个问题的,
自然而然的就以比例尺、道路类型这两个参数为key,道路宽度为value,建立的key如下:
但是编译的时候,报了这个错误
d:\program files\microsoft visual studio\vc98\include\functional(86) : error C2784: 'bool __cdecl std::operator <(const class std::multimap<_K,_Ty,_Pr,_A> &,const class std::multimap<_K,_Ty,_Pr,_A> &)' : could not deduce template argument for 'const
class std::multimap<_K,_Ty,_Pr,_A> &' from 'const struct tagRoadKey'
问题肯定出在这个key上面,后来百度了下,才知道原因,原来map中的key默认是以less<>升序对元素排序(排序准则也可以修改),也就是说key必须具备operator<对元素排序,也就是要重载<运算符,而平常我们的用的基本上都是基本类型元素作为key,所以就不存在这个问题了。
我的使用情景是,我需要根据不同的比例尺、道路类型这两个参数获取到对应的道路宽度,由于我是使用map解决这个问题的,
自然而然的就以比例尺、道路类型这两个参数为key,道路宽度为value,建立的key如下:
typedef struct tagRoadKey
2 {
3 int nType;
4 int nScale;
5 }
6 }ROADKEY;
但是编译的时候,报了这个错误
d:\program files\microsoft visual studio\vc98\include\functional(86) : error C2784: 'bool __cdecl std::operator <(const class std::multimap<_K,_Ty,_Pr,_A> &,const class std::multimap<_K,_Ty,_Pr,_A> &)' : could not deduce template argument for 'const
class std::multimap<_K,_Ty,_Pr,_A> &' from 'const struct tagRoadKey'
问题肯定出在这个key上面,后来百度了下,才知道原因,原来map中的key默认是以less<>升序对元素排序(排序准则也可以修改),也就是说key必须具备operator<对元素排序,也就是要重载<运算符,而平常我们的用的基本上都是基本类型元素作为key,所以就不存在这个问题了。
改正后的结构体如下:
typedef struct tagRoadKey
2 {
3 int nType;
4 int nScale;
5
6 bool operator <(const tagRoadKey& other) const
7 {
8 if (nType < other.nType) //类型按升序排序
9 {
10 return true;
11 }
12 else if (nType == other.nType) //如果类型相同,按比例尺升序排序
13 {
14 return nScale < other.nScale;
15 }
16
17 return false;
18 }
19 }ROADKEY;