具有类键和类值的 C++ STL 映射容器

标签 c++ map containers

假设我有这样一个类:

class Point
{
   private:
      int x, y;
   public:
      void setX(int arg_x) { x = arg_x; }
      void sety(int arg_y) { y = arg_y; }
      int getX() const { return x; }
      int gety() const { return y; }
};

现在我想要一张这样的 map :

map<Point, Point> m;

但是我需要第三个参数。我在cplusplus里读到这第三个参数是用来比较什么的,但是没看懂那是什么东西。谁能给我解释一下?

最佳答案

如果您不需要单独的比较函数,您可以使用这样的方法扩展您的类

class Point
{
   private:
      int x, y;
   public:

      bool operator<( const Point& other) const
      {
          if ( x == other.x )
          {
              return y < other.y;
          }

          return x < other.x;
      }
};

默认情况下,STL 映射通过某种排序概念对其中的所有元素进行排序。在这种情况下,使用此运算符。有时您无法控制 Point 类,或者您可能想在两个不同的 map 中使用它,每个 map 都定义了自己的顺序。例如,一张 map 可能首先按 x 对点进行排序,而另一张 map 可能首先按 y 对点进行排序。因此,如果比较运算符独立于类 Point 可能会有所帮助。你可以做这样的事情。

class Point
{
   public:
      int x, y;
};


struct PointComparer
{
    bool operator()( const Point& first , const Point& second) const
    {
        if ( first.x == second.x )
        {
            return first.y < second.y;
        }

        return first.x < second.x;
    }
};

map<Point, Point , PointComparer> m;

关于具有类键和类值的 C++ STL 映射容器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6973406/

相关文章:

c++ - 如何重载三元运算符(?:) in C++?

C++为什么不调用复制c'tor

php - 如何使用 Google Maps API 根据距离进行搜索?

Leaflet(Cloudmade)弹出窗口中的图像大小似乎不计算以确定弹出窗口的大小

ruby-on-rails - rails 3 的 map.connect 语法

c++ - std::set 和 < 运算符重载的奇怪行为?

c++ - 根据给定标准的最大总和

docker - 使构建 docker 任务更加高效

css - 导航使图像偏离中心

haskell - Haskell 中的非空集