2009-06-01 42 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