C++ - 标准::地图 不需要强制转换的替代方案

C++ - std::map Alternative that doesn't require casting

本文关键字:转换 方案 标准 地图 不需要 C++      更新时间:2023-10-16

我正在使用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;