Sorting a Vector in C++With Examples


In this tutorial, we are going to focus on Sorting a Vector in C++.

Sorting is one of the vastly performed operations in any programming language. Similarly, in C++ too, there are several algorithms following which we can sort any data structure.

For vectors, in particular, we can perform sorting operations in any order(ascending or descending).

Sorting a Vector in C++ in Ascending order

A vector in C++ can be easily sorted in ascending order using the sort() function defined in the algorithm header file.

The sort() function sorts a given data structure and does not return anything. The sorting takes place between the two passed iterators or positions. The third parameter determines the order in which the elements are going to be compared.

By default, for not passing the third parameter, the function considers it to be the std::less<int>() function. This function returns true or false on the basis of comparing two arguments, whether the first one is less than the other.

So, now let us see how we can sort a vector in C++(ascending order).


Sorting a Vector in C++ in Descending Order

As we said earlier, the third argument for the sort() function in C++ determines the order of sorting. So, we can define functions in it to sort any vector in our desired order(descending in this case).

1. Using greater<int>() in sort()

Similar to the less<int>() function, the greater<int>() function returns a bool value as true or false but in the opposite sense. If the first argument is greater than the second one, the function returns true and false if the above condition is false.

Let us see how we can use it to get a sorted vector in descending order.


2. Using Lambda Expression in sort()

Since C++11, the use of lambda expressions was introduced to C++ programming. They are nothing but simple one-line functions, which do not need declaration or even require to specify their return type.

Hence, we can use our own defined lambda expression to determine the order of sorting by the sort() function. This can be done by defining the one-line expression as the third parameter to the sort() function. Let see how


Here, the expression a>b is used to compare two passed arguments from the vector. As we can see from the output for the above code, the vector gets sorted in descending order as desired.


So, in this article, we learned about sorting a vectors in C++, in both ascending and descending order. For any further questions related to this topic, feel free to use the comments below.


By admin

Leave a Reply

%d bloggers like this: