2012-12-13 183 views
2

即時通訊嘗試使用排序函數對排序列表進行排序,其中包含對比較它們的第二個值的列表。這是我在用的:使用排序功能根據函數對列表進行排序

std::sort(score_list.begin(), score_list.end(), compare_pair); 

這是排序功能:

bool Highscore::compare_pair (std::pair<std::string, int> first, std::pair<std::string, int> second) 

{ 
    if (first.second<second.second) return true; 
    else return false; 
} 

和我收到此錯誤信息:

error: no matching function for call to ‘sort(std::list<std::pair<std::basic_string<char>, int> >::iterator, std::list<std::pair<std::basic_string<char>, int> >::iterator, <unresolved overloaded function type>)’ 

有什麼建議?謝謝

回答

3

您不能直接傳遞成員函數作爲比較器。當使用函數時,實際傳遞的是指向函數的指針 - 但指向函數的指針完全是,它與指向函數的指針不同。

C++ 98/03有幾個適配器,分別命名爲mem_funmem_fun_ref

C++ 11添加了mem_fn並棄用mem_funmem_fun_ref。假如你有一個足夠新的編譯器來包含它,它使用起來會容易多了。

如果你的編譯器是新的,但是,它可能會包括lambda表達式,它可以使任務相當清潔的,因爲你能給我們一個函數對象的「到位」的定義來處理比較:

typedef std::pair<std::string, int> data_t; 

std::sort(score_list.begin(), score_list.end(), 
    [](data_t const &a, data_t const &b) { 
     return a.second < b.second; 
    }); 

如果你的谷歌有類似「C++ 11 lambda」的東西,你應該找到更多關於這方面的信息(其中大部分幾乎肯定會直接返回到這裏)。

+0

+1:mem_fun也是我最初的直覺 – Chubsdad

2

另外,你幾乎可以肯定地想通過const引用而不是按值傳遞對你的排序函數。

static bool Highscore::compare_pair (const std::pair<std::string, int> &first, const std::pair<std::string, int> &second) 

and typedef是你的朋友。

1

如果您正在整理std::list,則應該使用std::list::sort成員函數。 std::sort算法要求隨機訪問迭代器std::list只提供雙向迭代器

相關問題