0

我对 std::sort 算法有疑问。这是我的测试代码:

struct MyTest
{
    int m_first;
    int m_second;

    MyTest(int first = 0, int second = 0) : m_first(first), m_second(second)
    {
    }
};


int main(int argc,char *argv[])
{
    std::vector<MyTest> myVec;
    for(int i = 0; i < 10; ++i)
    {
        myVec.push_back(MyTest(i, i + 1));
    }


    //Sort the vector in descending order on m_first without using stand alone function or functors


    return 0;

}  

m_first是否可以在不使用任何独立函数或仿函数的情况下对变量上的向量进行排序?另外,请注意我没有使用 boost。

4

6 回答 6

10

是的,只要要排序的范围内的值类型有一个operator <定义了“严格弱排序”的值,也就是说,它可以用来MyTest正确比较两个实例。您可能会执行以下操作:

class MyTest
{
  ...
  bool operator <(const MyTest &rhs) const
  {
    return m_first<rhs.m_first;
  }
};
于 2009-06-01T07:52:25.357 回答
3

为你的结构写一个 operator<。这是 sort 使用的默认函数,也是允许它在您的自定义数据结构上运行的最简单方法。

于 2009-06-01T07:51:01.490 回答
2

定义运算符<

struct MyTest
{
...
    bool operator<(const MyTest& a_test) const {
        return m_first < a_test.m_first;
    }
};
于 2009-06-01T07:51:49.087 回答
2

可以使用成员函数来做到这一点,但独立函数是要走的路。

bool operator <(const MyTest &lhs, const MyTest &rhs)
{
    return lhs.m_first<rhs.m_first;
}

为什么 ..

Scott Meyers:非成员函数如何改进封装

如果您正在编写一个可以实现为成员或非朋友非成员的函数,您应该更喜欢将其实现为非成员函数。该决定增加了类封装。当您考虑封装时,您应该考虑非成员函数。

惊讶吗?继续阅读

于 2009-06-01T08:57:31.437 回答
1

您应该定义一个operator<in MyTest,它应该如下所示:

bool operator<(const MyTest &other) const {
  return m_first < other.m_first;
};
于 2009-06-01T07:56:02.590 回答
-2

http://ideone.com/3QLtP

这没有定义运算符 <,但确实定义了函子。

但是,穿越时间或编译过程很有趣。

于 2011-08-28T10:40:23.083 回答