C++ - 标准::地图 不需要强制转换的替代方案
C++ - std::map Alternative that doesn't require casting
我正在使用std::映射来存储某些对象。该地图具有模板<Coordinate, Object>
。现在,我注意到地图将坐标转换为一个整数,然后在此基础上为元素提供一个唯一的键。(等于该整数)
现在,问题是不可能将一个三维整数(x,y,z)转换为std::map可以使用的单个整数。
std::map有哪些替代方案,它们确实要求键对象是唯一的,但不要求它被强制转换为整数(或字符串等)?
您可以使用Coordinate
作为映射的键。你只需要为它定义一个严格的弱排序(类似于小于或大于比较)。如何做到这一点取决于您,但例如,您可以使用以下3个坐标进行字典比较:
#include <tuple> // for std::tie
struct Coordinate
{
double x, y, z;
....
bool operator<(const Coordinate& rhs) const
{
return std::tie(x, y, z) < std::tie(rhs.x, rhs.y, rhs.z);
}
};
在这里,这是通过实现Coordinate
的les than运算符来完成的,但您也可以定义一个函子并使用它来构造映射:
struct Comp
{
bool operator()(const Coordinate& lhs, const Coordinate& rhs) const
{
return std::tie(lhs.x, lhs.y, lhs.z) < std::tie(rhs.x, rhs.y, rhs.z);
}
};
然后
std::map<Coordinate, ValueType, Comp> m;
相关文章:
- 如何将这种递归解决方案转换为分而治之?
- 将多个非原始递归调用转换为迭代解决方案
- 我在 TSP 的C++解决方案中遇到转换错误
- 如何在C VS2012中转换或创建.NET V3.5解决方案(特别是工具集)
- 数据转换解决方案
- 将递归解决方案转换为迭代解决方案
- 如何将递归解决方案转换为自下而上或自上而下的解决方案
- 将一维矩阵数组转换为主一维矩阵的有趣算法挑战,需要有效的解决方案
- C++ - 标准::地图 不需要强制转换的替代方案
- 如何将递归解决方案转换为迭代解决方案
- 将int转换为void*会丢失精度,在需要的情况下解决方案是什么
- 浮点<-> std::字符串转换替代方案?
- 将此自定义回合转换为数学更友好的解决方案
- 将'makefile.vc'转换为'.sln'解决方案文件
- 通用转换运算符模板和移动语义:有通用的解决方案吗
- c++ CLI - C++/CLI:为什么在此方案中没有托管>非托管转换?
- C++需要从常量字符串转换的解决方案
- 转换vc++解决方案和项目文件从32位到64位
- 如何在c++11中将迭代器转换为字符串?boost解决方案也可以
- Visual Studio 2010 2005解决方案的转换(c++项目)失去了项目依赖关系