How to sort vector in C++
Introduction
Sorting is a widely used operation in any computer language. Similarly, various methods in C++ can be used to sort any data structure.
Sorting procedures for vectors, in particular, can be performed in either sequence, like ascending or descending.
What exactly is sorting?
Sorting is the process of arranging array elements in a particular order. Sorting can be accomplished in either ascending (going from least to greatest) or descending (from greatest to bottom) order. This allows us to operate with this data type in the way we wish.
All human data is kept in some manner, which can be disorganized. Sorting is merely a method of organizing stuff. Every programmer needs to know sorting and methods to implement it in multiple programming languages.
sorting a vector in ascending order
Sorting a vector in the order of ascending is simple with the sort() method described in the procedure's header file. The sort() function organizes a datastructure but does not return any results. Sorting occurs between the two passed iterators or places. The third option specifies the order in which the elements will be compared.
By default, if the third parameter is not passed, the method considers it to be the std::lessint() function. Based on whether the initial parameter has a smaller value than the second, the sort method outputs either true or false.
So, let's examine at a way to sort a vector (in ascending sequence) in C++.
#include<iostream> #include<vector> #include<algorithm> using namespace std; int main() { //vector initialisation vector<int> vec {7, 9, 4, 8, 2}; cout<<"Before sorting vector : "; for(auto i=vec.begin(); i<vec.end(); i++) { cout<<" "<<*i; } std::sort(vec.begin(),vec.end()); cout<<"\n\nAfter sorting vector : "; for(auto i=vec.begin(); i<vec.end(); i++) { cout<<" "<<*i; } return 0; }
Output:
Sorting a vector in descending order
As previously stated, the order of sorting is determined by the third argument to the sort() method in C++. As a result, we can construct methods in it to sort any vector in the order we choose (descending in this example).
1. greaterint>() is used in sort().
The greaterint>() function, like the lessint>() function, returns a bool result as true or false, but in the opposite sense. The method returns true if the initial parameter has a higher value than the second; contrary, it returns false.
Let's have a peek at how to use it to obtain a sorted vector in descending order.
#include<iostream> #include<vector> #include<algorithm> using namespace std; int main() { //vector initialisation vector<int> vec { 7,2,8,3,6 }; cout<<"Before sorting vector : "; for(auto i=vec.begin(); i<vec.end(); i++) { cout<<" "<<*i; } std::sort(vec.begin(),vec.end(), greater<int>());//Sorting the vector using greater<int>() function cout<<"\n\nAfter sorting vector : "; for(auto i=vec.begin(); i<vec.end(); i++) { cout<<" "<<*i; } return 0; }
Output:
2. Sort() with a Lambda Expression
Lambda expressions have been used in C++ programming since C++11. They are one-line functions that do not require declaration or even specifying their return type. As a result, we can utilize our lambda expression to decide the sort() function's sorting order. This is accomplished by passing the one-line expression as the sort() function's third parameter. Let's see how it goes.
#include<iostream> #include<vector> #include<algorithm> using namespace std; int main() { //vector initialisation vector<int> vec { 7,2,13,21,5 }; cout<<"Before sorting vector : "; for(auto i=vec.begin(); i<vec.end(); i++) { cout<<" "<<*i; } std::sort(vec.begin(),vec.end(), [](int &g, int &h){ return g>h; }); //Sorting the vector using user-defined lambda expression cout<<"\n\nAfter sorting vector : "; for(auto i=vec.begin(); i<vec.end(); i++) { cout<<" "<<*i; } return 0; }
Output:
In this case, the statement g>his used to compare two vector arguments. The output for the given code shows that the vector is sorted in decreasing order as expected.
Sorting in a specific order
In addition, we can construct our comparator function and give it as a third parameter.
The comparator function evaluates if the outcome of the returned expression is true or false then offers a bool result to the sort function.
For example, suppose Interval i1 = {7, 8}and Interval i2 = {4, 2}. The comparator function distinguishes i1.start and i2.start when this is supplied to it. The comparison method returns false because i1.start (=7) < i2.start (=4). For instance, Interval i1 should not come before Interval i2. This function's code is shown below.
#include<iostream> #include<vector> #include<algorithm> //An interval has a beginning and an ending time. struct Interval { int start, end; }; compareInterval bool (Interval i1, Interval i2) { return (i1.start < i2.start); } int main() { vector<Interval> v { { 8, 3 }, { 3, 5 }, { 5, 6 }, { 1, 7 } }; // frame the intervals in ascending sequence of start time. sort(v.begin(), v.end(), compareInterval); cout << "Intervals sorted by start time: \n"; for (auto x : v) cout << "[" << x.start << ", " << x.end << "] "; return 0; }
Output: