C ++ - std :: map不需要转换的替代方法 [英] C++ - std::map Alternative that doesn't require casting

查看:356
本文介绍了C ++ - std :: map不需要转换的替代方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用std :: map来存储某些对象。地图有模板<坐标,对象> 。现在,我注意到,地图将坐标转换为一个整数,然后基于此给出元素一个唯一的键。 (等于该整数)

I am using an std::map to store certain objects. The map has the template <Coordinate, Object>. Now, what I noticed is that the map casts the Coordinate to an integer, and then based on that gives the element a unique key. (Equal to that integer)

现在,问题是将三维整数(x,y,z)转换为单个整数是不可能的,即std ::地图可以使用。

Now, the problem is that it's impossible to convert a 3 dimensional integer (x, y, z) to a single integer, that the std::map can use.

std :: map有什么替代方法,它要求密钥对象是唯一的,但不要求将其转换为整数(或字符串等) 。)?

What alternatives are there to std::map which do require the key object to be unique, but don't require it to be casted to an integer (or string etc.)?

推荐答案

您可以使用坐标作为键地图。您只需定义一个严格的弱订购(类似于较少的大于比较)。你如何做到这一点取决于你,但你可以使用3坐标执行词典比较:

You can use a Coordinate as a key to the map. You just have to define a strict weak ordering for it (something akin to a less-than or greater-than comparison). How you do that is up to you, but you could, for instance, perform a lexicographical comparison using the 3 coordinates:

#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);
  }
};

这里通过执行坐标,但您也可以定义一个函子并用它来构造地图:

Here, this is done by in the implementation of a les-than operator for Coordinate, but you can also define a functor and use it to construct the map:

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;

这篇关于C ++ - std :: map不需要转换的替代方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆