本文总结C++算法库中有关排序相关的库函数的常见用法。

1 std::sort

1.1 使用默认排序函数

默认排序函数得到的排序结果是升序结果。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
std::array<int, 10> s = {5, 7, 4, 2, 8, 6, 1, 9, 0, 3}; 

// sort using the default operator<
// 0 1 2 3 4 5 6 7 8 9
std::sort(s.begin(), s.end());
for (auto a : s) {
    std::cout << a << " ";
}   
std::cout << std::endl; 

// sort using a standard library compare function object
// 9 8 7 6 5 4 3 2 1 0
std::sort(s.begin(), s.end(), std::greater<int>());
for (auto a : s) {
    std::cout << a << " ";
}   
std::cout << std::endl;

1.2 使用自定义排序函数

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
// sort using a custom function
bool comp(const vector<int>& a, const vector<int>& b) {
    return *a.cbegin() < *b.cbegin();
}

vector<vector<int>> vec = {{5,6}, {2, 7}, {6, 9}, {15, 19}};
sort(vec.begin(), vec.end(), comp);
for (auto item : vec) {
    for (auto iter :  item) {
        printf("%d ", iter);
    }
    printf("\n"); 
}