C++ map以结构体为key的编译错误和解决方法
2011-12-13 11:55
676 查看
//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;
}
};
//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;
}
};
相关文章推荐
- C++编译错误解决方法总结
- 【转】比较有用的C++编译错误解决方法
- C++编译全攻略-编译器处理及LNK错误的解决方法(ZZ)
- dev-c++中编译含WINSOCK的代码出现错误的解决方法
- 引用原因.NET下编译C++代码时出现fatal error C1083: 无法打开包含文件:“iostream.h”: No such file or directory错误的解决方法.
- C++编译错误解决方法
- .NET下编译C++代码时出现"error C4430: 缺少类型说明符 - 假定为 int。注意: C++ 不支持默认 int"错误的解决方法。
- 类语句.NET下编译C++代码时出现"error C4430: 缺少类型说明符 - 假定为 int。注意: C++ 不支持默认 int"错误的解决方法。
- C++常见gcc编译链接错误解决方法
- VS2015 C++编译失败,提示link1171,无法加载mspdb140.dll错误解决方法!
- 项目文件.NET下编译C++代码时出现fatal error C1083: 无法打开包括文件:“xuhk_JNIHelloWorld.h”: No such file or directory错误的解决方法。
- C/C++常见gcc编译链接错误解决方法
- .NET下编译C++代码时出现fatal error C1083: 无法打开包含文件:“iostream.h”: No such file or directory错误的解决方法.
- C/C++/MFC 编译运行错误解决方法收集error
- C++常见gcc编译链接错误解决方法
- C++编译错误"a storage class can only be specified for objects and functions"解决方法
- C/C++编译时的Link.EXE错误问题与解决方法
- C/C++编译链接错误解决方法 汇总
- C++编译错误syntax error : identifier 'THIS_FILE' 解决方法
- C++编译错误解决方法