2009-06-01 106 views
0

我有一个关于std :: sort算法的问题。这里是我的测试代码:std ::排序没有函子

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矢量进行排序,而无需使用任何独立的函数或仿函数?另外,请注意,我没有使用提升。

回答

10

是,只要在待分选的范围中的值的类型有一个operator <限定“严格弱排序”,也就是说,它可以用于操作者正确比较两个MyTest实例。你可以这样做:

class MyTest 
{ 
    ... 
    bool operator <(const MyTest &rhs) const 
    { 
    return m_first<rhs.m_first; 
    } 
}; 
3

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

2

定义<

struct MyTest 
{ 
... 
    bool operator<(const MyTest& a_test) const { 
     return m_first < a_test.m_first; 
    } 
}; 
+0

操作员应该只带一个参数并与“this”进行比较。 – sth 2009-06-01 07:58:02

+0

是的,修好了,谢谢! – 2009-06-01 08:03:29

1

你应该MyTest定义operator<,它应该是这样的:

bool operator<(const MyTest &other) const { 
    return m_first < other.m_first; 
}; 
2

这是可能的一个成员函数,但独立的功能就是去做要走的路。

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

为什么..

斯科特迈尔斯:非成员函数如何提高封装

如果你正在编写可 被实现为会员或 功能作为非朋友的非会员,您应该更愿意将其作为非会员 函数来实现。该决定增加了 类封装。当你认为 封装时,你应该认为 非成员函数。

Surprised? Read on