2011-11-14 158 views
13

我想要一個stl list的對象,其中每個對象包含兩個int's。 之後,我想在第一個int的值之後用stl :: sort對列表進行排序。 如何告訴排序功能它應該在第一個int之後排序?排序自定義類型的列表

回答

24

您可以指定自定義排序謂詞。

typedef std::pair<int, int> ipair; 
std::list<ipair> thelist; 

thelist.sort([](const ipair & a, const ipair & b) { return a.first < b.first; }); 

在老版本的C++,你必須寫一個適當的功能:在C++ 11,這是最好用的λ完成

bool compFirst(const ipair & a, const ipair & b) { return a.first < b.first; } 

thelist.sort(compFirst); 

(相反,如果ipair當然你也可以有你自己的數據結構;只需修改比較函數即可訪問相關數據成員。)

最後,如果這樣做有道理,也可以使用operator<裝備您的自定義類。這使您可以在任何有序的環境中自由使用該類,但一定要理解其後果。

+0

您好。我使用的是「舊版本」排序,但它保留了一個未排序的元素:原始列表中的最後一個元素沒有排序,它始終是最後一個元素。你知道什麼可能是錯的嗎?謝謝 –

+0

@MarcoCastanho:我不認爲這會發生。聽起來就像你在某個地方有bug。隨意發佈一個問題;請務必創建一個*最小*再現示例。 –

2

std :: list :: sort has a one-argument form,第一個參數是比較函數。

+1

'std :: sort'也不能在'std :: list's ... :-( –

+2

@KerrekSB:謝謝。有一天我會追捕那個決定std :: sort不能的人只是專門用於列表迭代器,但必須被合併到類中 – thiton

+0

不要,它沒有意義列表排序是完全不同的,並且與迭代器無關標準排序通過*交換值* ,而列表排序利用了容器的本性,並且只是重新綁定了元素節點。注意,列表排序不會*接受迭代器對! –

1

你可以做這樣的事情:

typedef std::pair<int,int>; 
list<my_type> test_list; 

bool my_compare (my_type a, my_type b) 
{ 
    return a.first < b.first; 
} 

test_list.sort(my_compare); 

如果類型是一個結構或類它的工作是這樣的:

struct some_struct{ 
    int first; 
    int second; 
}; 

list<some_struct> test_list; 

bool my_compare (const some_struct& a,const some_struct& b) 
{ 
    return a.first < b.first; 
} 

test_list.sort(my_compare); 

或者你也可以定義operator <爲你的結構和只需撥打電話test_list.sort()