Sorting sequence containers with specifed ordering

suggest change

If the values in a container have certain operators already overloaded, std::sort can be used with specialized functors to sort in either ascending or descending order:

#include <vector>
#include <algorithm>
#include <functional>

std::vector<int> v = {5,1,2,4,3};

//sort in ascending order (1,2,3,4,5)
std::sort(v.begin(), v.end(), std::less<int>());

// Or just:
std::sort(v.begin(), v.end());

//sort in descending order (5,4,3,2,1)
std::sort(v.begin(), v.end(), std::greater<int>());

//Or just:
std::sort(v.rbegin(), v.rend());

In C++14, we don’t need to provide the template argument for the comparison function objects and instead let the object deduce based on what it gets passed in:

std::sort(v.begin(), v.end(), std::less<>());     // ascending order
std::sort(v.begin(), v.end(), std::greater<>());  // descending order

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:


Sorting:
* Sorting sequence containers with specifed ordering

Table Of Contents
8 Arrays
11 Loops
39 Streams
51 Unions
56 Lambdas
60 SFINAE
62 RAII
67 Sorting
84 RTTI
87 Scopes
104 Profiling
107 Recursion
117 Iteration
125 Alignment
134 Semaphore
136 Debugging
139 Mutexes
142 decltype