Tutorial by Examples

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: C++11 #include <vector> #include <algorithm> #include <functional> std::vector<int> v = {5,1,2,4,3};...
If no ordering function is passed, std::sort will order the elements by calling operator< on pairs of elements, which must return a type contextually convertible to bool (or just bool). Basic types (integers, floats, pointers etc) have already build in comparison operators. We can overload this ...
// Include sequence containers #include <vector> #include <deque> #include <list> // Insert sorting algorithm #include <algorithm> class Base { public: // Constructor that set variable to the value of v Base(int v): variable(v) { } i...
C++11 // Include sequence containers #include <vector> #include <deque> #include <list> #include <array> #include <forward_list> // Include sorting algorithm #include <algorithm> class Base { public: // Constructor that set variable to the va...
std::sort, found in the standard library header algorithm, is a standard library algorithm for sorting a range of values, defined by a pair of iterators. std::sort takes as the last parameter a functor used to compare two values; this is how it determines the order. Note that std::sort is not stable...
This example sorts elements in ascending order of a key using a map. You can use any type, including class, instead of std::string, in the example below. #include <iostream> #include <utility> #include <map> int main() { std::map<double, std::string> sorted_map; ...
The sort algorithm sorts a sequence defined by two iterators. This is enough to sort a built-in (also known as c-style) array. C++11 int arr1[] = {36, 24, 42, 60, 59}; // sort numbers in ascending order sort(std::begin(arr1), std::end(arr1)); // sort numbers in descending order sort(std::b...

Page 1 of 1