# Sorting
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
The comparison function must impose a Strict, Weak Ordering
(opens new window) on the elements. A simple less-than (or greater-than) comparison will suffice.
A container with random-access iterators can be sorted using the std::sort algorithm:
std::sort requires that its iterators are random access iterators. The sequence containers std::list and std::forward_list (requiring C++11) do not provide random access iterators, so they cannot be used with std::sort . However, they do have sort member functions which implement a sorting algorithm that works with their own iterator types.
Their member sort functions always sort the entire list, so they cannot sort a sub-range of elements. However, since list and forward_list have fast splicing operations, you could extract the elements to be sorted from the list, sort them, then stuff them back where they were quite efficiently like this:
# Sorting sequence containers with specifed ordering
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:
In C++14, we don’t need to provide the template argument for the comparison function objects and instead let the object deduce based on what it gets passed in:
# Sorting sequence containers by overloaded less operator
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 operator to make the default sort call work on user-defined types.
# Sorting sequence containers using compare function
# Sorting sequence containers using lambda expressions (C++11)
# sorting with std::map (ascending and descending)
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.
If entries with equal keys are possible, use multimap instead of map (like in the following example).
To sort elements in descending manner, declare the map with a proper comparison functor ( std::greater<> ):
# Sorting built-in arrays
The sort algorithm sorts a sequence defined by two iterators. This is enough to sort a built-in (also known as c-style) array.
Prior to C++11, end of array had to be "calculated" using the size of the array:
Сортировать vector в порядке убывания в C++
В этом посте мы обсудим, как сортировать vector в порядке убывания в C++.
1. Используйте std::sort (или же std::stable_sort )
Эффективным решением является использование std::sort алгоритм, определенный в <algorithm> заголовок. Обычно это высокоэффективная реализация Алгоритм интросортировки, который начинается с быстрая сортировка и переключается на сортировка кучей когда рекурсия идет слишком глубоко.
The std::sort алгоритм не поддерживает относительный порядок равных элементов. Чтобы получить стабильную сортировку, используйте std::stable_sort , который использует Сортировка слиянием алгоритм.
Версия с двумя аргументами std::sort алгоритм сортирует vector в порядке возрастания, используя operator< . Чтобы получить порядок убывания, позвоните по номеру std::reverse после std::sort .
Sorting a vector in C++

Although one can sort a vector manually using one of the many available sorting algorithms, using a function from the C++ STL(Standard Template Library) can make the job easier.
The function used is the std::sort defined in the algorithm header. This sort() uses the introsort algorithm which is a hybrid sorting algorithm that uses quick sort, heap sort and insertion sort. It begins with quicksort, it switches to heapsort when the recursion depth exceeds a level based on (the logarithm of) the number of elements being sorted and it switches to insertion sort when the number of elements is below some threshold. This combines the good parts of the three algorithms, with practical performance comparable to quicksort on typical data sets and worst-case O(nlogn) runtime due to the heap sort. Since the three algorithms it uses are comparison sorts, it is also a comparison sort.
The basic syntax of this function is:
and the class definition is as follows:
The sort(), sorts from first to last index.
The different ways to sort a vector in C++ are:
- Ascending order
- Descending order
- Custom comparison function
- Using a lambda to sort
- Sorting only specific elements in a vector
- basic method
- std::nth_element()
- std::nth_element() + comp
- sort a specific row
- sort a specific column
We will, now, go through each technique in detail.
1) Ascending order
The basic syntax is:
Go through this example to understand the process:
The sort() also takes a third parameter to change the order of the numbers
2) Descending order
greater<int>() can be used, as the third parameter to sort the vector in a decreasing order. It will be used as:
Go through this example to understand the process:
Using a comp function
This is a user defined comparator function, where the user can define the way they want to sort the data. We can use the same function to sort the vector in a decreasing order without using the greater<int>()
The syntax is as follows:
Go through this example to understand the process:
This cmp becomes extremely useful when one has to compare a vector of pairs, or any such combinational data types.
Using a lambda to sort
With C++ 11 we can pass lambda to a sort function. In the given example we simply sorted the data in decreasing order but without passing a third argument, we passed the lambda that took care of it.
Lambda is an inline function that can be used for short snippets of code that are not going to be reused. The return type of this function is evaluated by the compiler. It is used as follows:
Go through this example to understand the process:
Sorting only specific elements in a vector
std::nth_element()
This function does not sort the entire vector, only sorts in such a way that the nth element in the vector if sorted will be in place, and all
Go through this complete example to understand the process better:
Using a cmp function
The basic syntax is as follows:
Go through this complete example to understand the process better:
3) sorting a 2D vector
A 2D vector is vector of vectors. It is an matrix implemented with the help of vectors.
The syntax of the function is pretty much the same, however since the vector is 2D, we can change the order in many ways (row sorted, column sorted, size sorted etc)sorting based on a particular row
Sorting a specific row is simple as we can directly specify row in the sort method as follows:
Go through this complete example to understand the process better:
The Matrix before sorting 3rd row is:
The Matrix after sorting 3rd row is:
sorting a column in 2D matrix
We can take help from the comparator function to sort a single column in a 2D matrix. The basic syntax is as follows:
Go through this example to understand the process:
Time Complexity
std::sort have average case linearithmic (n log n) time complexity, where n being distance between first to last.
std::nth_element(): O(n), with n being the distance between first and the last.
Applications
Sorting forms a core building block in structuring algorithms to solve the problems of data in real world by sorting the given data according to the requirements.
Question
Which algorithm is used in sort() in C++?
With this, you will have the complete knowledge of sorting a vector in any way. Enjoy.

K. Sai Drishya
Love music; Student at Gandhi Institute of Technology and Management (GITAM); Intern at OpenGenus
Improved & Reviewed by:
OpenGenus Tech Review Team
Software Engineering
Create a Web App using Flask to present a Machine Learning model
We will see how to deploy a Machine Learning model by building a simple Web Application using Flask. It will run the Machine Learning model in the server as inference.
Akshat Maheshwari
Searching tweets using the standard Search API of Twitter
Standard search API is a part of Twitter API which is used to send search queries to the twitter server. It searches the desired query in the twitter server and returns the tweet data and its various parameters.
Sorting a Vector in C++

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.
Introduction
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).
Output:
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.
Output:
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
Output:
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.
Conclusion
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.
References
-
— JournalDev Tutorial, — C++ algorithm Library, — StackOverflow Question, — StackOverflow Question.
Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.