C++ map以结构体为key的编译错误和解决方法

来源:互联网 发布:帝国cms 7.2最新漏洞 编辑:程序博客网 时间:2024/06/08 03:06

//map 

//define

struct TempCoeffIndex
{
int tempClass;
int sfc;
};

mutable std::map<TempCoeffIndex,float>CONST_TEMP_COEFF;


// insert data into map

SCC::TempCoeffIndex tempIndex={0};

for(int i=0;i<4;++i)
{
tempIndex.tempClass = i+1;
for(int j=0;i<18;++j)
{
tempIndex.sfc = j+1;

CONST_TEMP_COEFF.insert(make_pair(tempIndex,i*j));
}
}


// compile 

c:\program files\microsoft visual studio 9.0\vc\include\functional(143) : error C2678: 二进制“<”: 没有找到接受“const SCC::TempCoeffIndex”类型的左操作数的运算符(或没有可接受的转换)


// cause

原因,map中的key默认是以less<>升序对元素排序(排序准则也可以修改),也就是说key必须具备operator<对元素排序,而平常我们的用的基本上都是基本类型元素作为key,所以就没有问题


// solution

//重写operator < ()

struct TempCoeffIndex
{
int tempClass;
int sfc;

bool operator <(const TempCoeffIndex& rs) const
{
if(tempClass < rs.tempClass)
{
return true;
}
else if(tempClass == rs.tempClass)
{
return sfc < rs.sfc;
}
return false;
}
};