array sort in c++ code example

Example 1: stl sort in c++

sort(arr, arr+n); // sorts in ascending order

Example 2: array sort c++

#include <iostream>
2 #include <array>
3 #include <string>
4 #include <algorithm>
5
6 using namespace std;
7
8 int main(){
9 array<string, 4> colours = {"blue", "black", "red", "green"};
10 for (string colour : colours){
11 cout << colour << ' ';
12 }
13 cout << endl;
14 sort(colours.begin(), colours.end());
15 for (string colour : colours){
16 cout << colour << ' ';
17 }
18 return 0;
19 }
66
20
21 /*
22 Output:
23 blue black red green
24 black blue green red
25 */

Example 3: stl sort in c++

sort(arr, arr+n, greater<int>()); // sorts in descending order

Example 4: c++ sort

std::vector s = {5, 1, 3, 6, 2,};
std::sort(s.begin(), s.end());

Tags:

Cpp Example