std::sort的详细用法

Posted hchacha

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了std::sort的详细用法相关的知识,希望对你有一定的参考价值。

 1 #include <algorithm>
 2 #include <functional>
 3 #include <array>
 4 #include <iostream>
 5 
 6 int main()
 7 {
 8     std::array<int, 10> s = { 5, 7, 4, 2, 8, 6, 1, 9, 0, 3 };
 9 
10     // sort using the default operator<
11     std::sort(s.begin(), s.end());
12     for (auto a : s) {
13         std::cout << a << " ";
14     }
15     std::cout << \n;
16 
17     // sort using a standard library compare function object
18     std::sort(s.begin(), s.end(), std::greater<int>());
19     for (auto a : s) {
20         std::cout << a << " ";
21     }
22     std::cout << \n;
23 
24     // sort using a custom function object
25     struct {
26         bool operator()(int a, int b) const
27         {
28             return a < b;
29         }
30     } customLess;
31     std::sort(s.begin(), s.end(), customLess);
32     for (auto a : s) {
33         std::cout << a << " ";
34     }
35     std::cout << \n;
36 
37     // sort using a lambda expression 
38     std::sort(s.begin(), s.end(), [](int a, int b) {
39         return b < a;
40     });
41     for (auto a : s) {
42         std::cout << a << " ";
43     }
44     std::cout << \n;
45 }

 

以上是关于std::sort的详细用法的主要内容,如果未能解决你的问题,请参考以下文章

C++ - 使用 std::sort 对结构向量进行排序导致读取访问冲突

C++ 标准库 sort() / stable_sort() / partial_sort() 对比

对空向量进行 std::sort [关闭]

vector中的升序算法是sort()但降序算法是什么呀?求用法?

B00012 C++算法库的sort()函数

源码阅读笔记 - 1 MSVC2015中的std::sort