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

社会主义新天地 提交于 2019-12-25 07:26:46

问题


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)

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.

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.)?


回答1:


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

then

std::map<Coordinate, ValueType, Comp> m;


来源:https://stackoverflow.com/questions/17911963/c-stdmap-alternative-that-doesnt-require-casting

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!