【问题标题】:Overloading " < " for STL sort()为 STL sort() 重载“<”
【发布时间】:2014-12-07 08:49:25
【问题描述】:

我创建了一个结构,其中包含两个 long long int 类型的变量,例如 xy

我可以通过重载 &lt; 运算符并根据任何一个变量进行排序来使用 STL sort()

struct point
{
    long long int x, y;
};

bool compare(point lhs, point rhs)
{    
    return lhs.x < rhs.x;
}

sort(point, point + t, compare);

我要做的是根据x对结构进行排序,但是当两个桶的x值相同时,应该首先放置y值较小的桶。 我怎样才能做到这一点?

【问题讨论】:

  • 只是为了记录,您没有在此处对&lt; 进行任何重载。

标签: c++ stl operator-overloading


【解决方案1】:

比较xy的元组:

bool compare(point lhs, point rhs)
{    
    return std::tie(lhs.x, lhs.y) < std::tie(rhs.x, rhs.y);
}

这正是你想要的。

std::tie 的参考页面甚至有一个与您正在做的事情基本相同的示例。

【讨论】:

    【解决方案2】:

    这正是你所说的:

    bool compare(point lhs, point rhs)
    {    
        return (lhs.x == rhs.x)
             ? (lhs.y < rhs.y)
             : (lhs.x < rhs.x);
    }
    

    另外,std::sort() 的比较器应该采用 const lvalue-references:

    bool compare(point const& lhs, point const& rhs);
    

    【讨论】:

      【解决方案3】:
      inline bool compare(const point& lhs, const point& rhs)
      {    
         if (lhs.x < rhs.x)
             return true;
         if (lhs.x > rhs.x)
             return false;
         return lhs.y < rhs.y;
      }
      

      【讨论】:

        猜你喜欢
        • 2014-12-29
        • 2021-06-03
        • 1970-01-01
        • 2018-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-03-08
        • 2010-10-16
        相关资源
        最近更新 更多