Note 21.10.1.
cppreference.com is a great resource for exploring what is available in the standard algorithms library.
sort on an unordered_map because it does not have a defined order. It is completely meaningless to try putting in order things that do not provide any way to talk about which item comes before another.
iterators and operator overloading. The code in the algorithms is written in terms of these abstractions. They do not know or care if they happen to be working with a vector, a set, or some other kind of collection. As long as the collection provides the necessary interface the algorithms can operate on the collection.
sets can rely on functors to specify how to order their elements, some algorithms also take functions (or functors) as parameters to customize their behavior. For example, the sort algorithm can take a comparison function to specify how to compare elements when sorting.
std::sort looks like something like this:
void sort( RandomIt first, RandomIt last, Compare comp );
RandomIt is a type that represents an iterator that can move through a collection in random order (like the iterators provided by a vector). This means you could not use this algorithm with containers that do not provide random access to their elements. The first and last parameters specify the range of elements to sort. The optional comp parameter is a comparison function that defines how to compare two elements.
sort function.
sort(myVector.begin(), myVector.end());
last parameter to point to the iterator 10 positions from the beginning:
sort(myVector.begin(), myVector.begin() + 10);
bool Compare(const T& a, const T& b);
a should come before b in the sorted order, and false otherwise. So, for descending order, we would want to return true if a is greater than b:
bool DescendingComparer(int a, int b) {
return a > b; // a comes first if it is greater than b
}
> operator. The standard library already provides a functor for that operator called std::greater<T>. So, we could have used that instead of writing our own comparison function. Here is how that would look:
sort(numbers.begin(), numbers.end(), std::greater<int>());
() after std::greater<int> to create an instance of the functor. It is an object that behaves like a function, not a function.
v using default ordering. You will not need all the blocks.