如何使用C++的標準函式庫進行排序? (C/C++) (STL)
时间:2010-10-26 来源:李sir
Introduction
STL的sort()不僅僅支援array,還支援其餘的container如vector,list等,這也是泛型之美,container和algorithm徹底decouple,讓algorithm可以支援各種container,達到最大的reuse,由於STL是C++ 98的標準,所以跨平台不是問題。
GenericAlgo_sort.cpp
1
/**//*
2
(C) OOMusou 2007 http://oomusou.cnblogs.com
3
4
Filename : GenericAlgo_sort.cpp
5
Compiler : Visual C++ 8.0
6
Description : Demo how to use sort()
7
Release : 01/29/2008 1.0
8
*/
9
10
#include <iostream>
11
#include <algorithm>
12
#include <functional>
13
14
using namespace std;
15
16
int main()
{
17
int ia[] =
{2, 3, 1 ,3 ,5};
18
int arr_size = sizeof(ia) / sizeof(int);
19
20
copy(ia, ia + arr_size, ostream_iterator<int>(cout, " "));
21
22
cout << endl;
23
24
sort(ia, ia + arr_size);
25
// sort(ia, ia + arr_size, less<int>()); // OK
26
27
copy(ia, ia + arr_size, ostream_iterator<int>(cout, " "));
28
}

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16


17


18

19

20

21

22

23

24

25

26

27

28

執行結果
2 3 1 3 5
1 2 3 3 5 請按任意鍵繼續 . . .
1 2 3 3 5 請按任意鍵繼續 . . .
20行和27行只是透過copy()將目前的陣列顯示出來,不是重點。
24行的sort()才是真正的對陣列作排序,第一個參數為陣列的起始元素記憶體位址,第二個參數為陣列最後一個元素的記憶體位址,由於sort()預設就是由小排到大,因此可以忽略第三個參數,當然如26行加上less<int>()這個predicate亦可。
Conclusion
本文我們看到了使用C++的方式作排序,使用STL的sort() algorithm。
相关阅读 更多 +
排行榜 更多 +