2016-05-13 76 views
0

對std :: list 進行排序我想根據參數對列表std :: list進行排序。例如: 使用myclass :: operator [](int i)

class myclass 
{ 
    string name, surname; 
public: 
    myclass() {} 
    ~myclass() {} 
    string operator[](int i) 
    { 
     switch (i) 
     { 
     case 1: return name; 
     case 2: return surname; 
     } 
    } 
}; 

template <typename T> 
struct compare 
{ 
    int num; 
    indirect_compare() {} 
    indirect_compare(int i) : num(i) {} 
    ~indirect_compare() {} 
    bool operator()(T * lhs, T * rhs) { return (*lhs)[num] < (*rhs)[num]; } 
}; 

list<myclass*> lst; 
int specified_by_user; 
cin >> specified_by_user; 

//later 

lst.sort(compare<myclass>(specified_by_user)); 

它適用於我,但我不確定它是否正確。當我在結構比較中的構造函數和析構函數中添加了一些消息時,我看到構造函數僅被調用一次,但析構函數被調用了9次,我不知道爲什麼會發生。我試圖調試這個程序來檢查它,但我找不到原因。

感謝您的幫助!

+2

的其他構造很可能是拷貝構造函數。你有沒有監視那個? – Sheph

+0

比較的ctor和dtor被命名爲indirect_compare。這個例子是否編譯?如果使用無效,也可以擺脫無參數。 – Sheph

+0

'不確定它是否正確'對我來說看起來是正確的,有幾種不同的方法可以做到這一點,但你的並不是錯誤的 – vu1p3n0x

回答

1

我會嘗試將運算符[]切換到比較函數對象(可能甚至使用lambda代替)。這將允許您比較不屬於同一類型的屬性。 (例如,如果你添加一個成員int age;

另外我會有一個事物列表,而不是指向事物的指針列表你可能會得到1個構造函數和多個刪除問題,因爲你不夠細緻的指針。

事情是這樣的:

struct myclass 
{ 
    string name; 
    string surname; 
}; 

template <typename T> 
struct compare 
{ 
    int num; 
    compare() {} 
    compare(int i) : num(i) {} 
    ~compare() {} 
    bool operator()(const T & lhs, const T & rhs) { 
    switch(num) 
    { 
     case 1: return lhs->name < rhs->name; 
     case 2: return lhs->surname < rhs->surname; 
     default: throw std::logic_error(); 
    } 
    } 
}; 

list<myclass> lst; 
+0

感謝您的回答!這個想法很好,但我想保留成員名稱和姓氏私人,因爲我的班級中有更多的字符串,我不想爲每個成員創建getter和setter。這就是我使用operator []的原因。 – Ben

0

你的代碼看起來不錯您的解決方案是有點不尋常,但它是否適合你去爲它在米爾恰·巴哈的精神,我想展現!你爲你的問題提供了另一種解決方案,只是爲了獲得靈感:

if (specified_by_user) // sort by name 
    lst.sort(auto [](auto const & a, auto const & b){ return a.name < b.name; }); 
else // sort by surname 
    lst.sort(auto [](auto const & a, auto const & b){ return a.surname < b.surname; }); 

首先,我們決定根據哪個字段將您的類和客戶端代碼整理出來。其次,我們沒有定義比較器結構,而是將lambdas傳遞給lst.sort(),它可以非常簡潔地定義,內聯在函數調用本身中。

這意味着字段名稱和姓氏是公開的(所以lambda可以訪問它們)。如果你想保持他們的私人,您可以添加干將到您的類,而不是:

string const & get_name() const { return name; } 

,並稍微改變lambda表達式:

auto [](auto const & a, auto const & b){ return a.get_name() < b.get_name(); } 
+0

這很好,但我想保留成員姓名和私人名稱,因爲我的班級中有更多的字符串,我不想爲每個成員創建getter和setter(特別是我只在這種情況下使用它們)。這些比較以相同的方式工作,所以我試圖縮短我的代碼。這就是我使用operator []的原因。 – Ben

相關問題