Sort a vector in C++

In this post, we will discuss how to sort a vector of integers in C++ in ascending order.


The recommended approach is to use the standard algorithm std::sort defined in the <algorithm> header. It is usually implemented using a hybrid algorithm like Introsort, which combines quicksort with heapsort and insertion sort and produces an unstable sort i.e. the relative order of elements with equal values is not preserved.

It has two overloaded versions –

1. The first version just takes the iterators to the initial and final positions of the vector and sorts the elements in increasing order using std::less which will delegate to operator<.


Download   Run Code


2 3 4 5 7

2. The second version takes a comparator to define the ordering of elements. The comparator is a binary predicate which compares its two arguments and return a boolean value that determines whether the first argument goes before the second argument in the sorted sequence.

The two-arg version of std::sort uses the default value of std::less for the optional third argument. Below code passes std::less function object in std::sort as a comparator which returns true if the first argument is less than the second argument. With C++14, we can even skip the template arguments. So, std::less<int>() becomes std::less<>().


Download   Run Code

We can also pass our own function object to std::sort method. We just need an instance of a class with operator() defined.


Download   Run Code

The third argument can be a simple binary function as shown below:


Download   Run Code

With C++11, we can even pass a lambda to std::sort function to define the ordering.


Download   Run Code



1. To get a stable sort, consider using std::stable_sort which is like std::sort but maintains the relative order of equal elements.

2. We can also write our own efficient routine for sorting the vector using quicksort, mergesort algorithms, etc.

3. With C++11, we can use std::is_sorted to check if a vector is sorted or not. It is defined in the header <algorithm>.

1 Star2 Stars3 Stars4 Stars5 Stars (1 votes, average: 5.00 out of 5)


Thanks for reading.

Please use our online compiler to post code in comments. To contribute, get in touch with us.
Like us? Please spread the word and help us grow. Happy coding 🙂

Leave a Reply

Notify of