Sort Containers with std::sort()
Learn to sort containers with std::sort.
We'll cover the following...
The problem of how to efficiently sort comparable elements is essentially solved. For most applications, there's no reason to re-invent this wheel. The STL provides an excellent sorting solution via the std::sort() algorithm. While the standard does not specify a sorting algorithm, it does specify a worst-case complexity ofn elements.
Just a few decades ago, the quicksort algorithm was considered a good compromise for most uses and was generally faster than other comparable algorithms. Today we have std::sort() provides exceptional performance under most common circumstances.
How to do it
In this recipe, we'll examine the std::sort() algorithm. The sort() algorithm works with any container with random-access iterators. Here, we will use a vector of int:
We'll start with a function to test if a container is sorted: