2013-03-31 39 views
0

我得到了一個用戶可以定義哪些字符串值在哪裏的結構。我試着按字母順序排列,但沒有發現我在網上發現的研究成果。我希望,如果使用的人能看到我去錯了C++使用排序結構的麻煩

庫使用:iostream的,字符串的fstream和算​​法

struct House 
{ 
    int room_num;    
    string person;  
}; 

struct compare_by_word 
{ 
    bool operator()(const House& lhs, const House& rhs) 
    { 
     return lhs.person < rhs.person; 
    } 
}; 

我使用視覺工作室2010得到錯誤在這條線上,順便IM

void asc_order() 
    { 
     sort(data.begin(), data.end(), compare_by_word()); 
//for loop will be displayed here to show table 
    } 

錯誤,我得到:

錯誤:標識符數據不確定

結構compare_by_word 錯誤:類型名稱是不允許

+0

數據應被宣佈。我們假設這個代碼只是一個片段。進行示範。在調用'sort'之前,你需要在'asc_order'的''代碼的某個地方有'vector 數據''。希望填補一些房屋。 – 2013-03-31 21:50:27

回答

1

您需要通過compare_by_word的實例。這是通過調用它的構造函數中完成:

std::sort(data.begin(), data.end(), compare_by_word()); 
//         ^^^^^^^^^^^^^^^^^ 

Live Demo

我也看到你不認爲引進與beginend方法的對象任何頭編譯。這些通常用於向量和其他動態容器。所以,我想你應該嘗試傳遞的地址範圍,而不是作爲可行的替代:

std::size_t len = sizeof(data)/sizeof(*data); 

std::sort(data, data + len, compare_by_word()); 

Live Demo

或者如果你在編譯C++ 11,你可以在地方一個明確的仿函數傳遞一個lambda回調並使用beginend庫函數而不是地址範圍的:

using std::begin; 
using std::end; 

std::sort(begin(data), end(data), [] (House const& lhs, House const& rhs) 
{ 
    return lhs.person < rhs.person; 
}); 

Live Demo

+0

您應該...重新排列示例中的元素。它工作得很好,但它並沒有真正表明這種行爲正在做任何事情。 – Xymostech

+0

@Xymostech是的,也許我應該把它們混合一下。 :) – 0x499602D2

+0

好多了! :) – Xymostech

2

你傳遞作爲比較。您需要通過對象compare_by_word作爲比較器sort

0

另一種方法是

struct compare_by_word 
{ 
    bool operator()(const House& lhs, const House& rhs) 
    { 
     return lhs.person < rhs.person; 
    } 
} compare_by_word; // Here. 
+0

替代什麼?.. – SomeWittyUsername

+0

到我之前提供的答案 – 2013-03-31 21:47:33

0

有一個在排序 statement.Replace它的一個錯誤是:

sort(&data[0],&data[5],compare_by_word()); 

DEMO AT IDEONE