Sorting a vector in C++
Last Updated :
11 Jan, 2023
Prerequisites : std::sort in C++, vector in C++, initialize a vector in C++.
CPP
#include <bits/stdc++.h>
using namespace std;
int main()
{
vector< int > v{ 1, 5, 8, 9, 6, 7, 3, 4, 2, 0 };
sort(v.begin(), v.end());
cout << "Sorted \n" ;
for ( auto x : v)
cout << x << " " ;
return 0;
}
|
Output
Sorted
0 1 2 3 4 5 6 7 8 9
How to sort in descending order?
sort() takes a third parameter that is used to specify the order in which elements are to be sorted. We can pass “greater()” function to sort in descending order. This function does comparison in a way that puts greater elements before.
CPP
#include <bits/stdc++.h>
using namespace std;
int main()
{
vector< int > v{ 1, 5, 8, 9, 6, 7, 3, 4, 2, 0 };
sort(v.begin(), v.end(), greater< int >());
cout << "Sorted \n" ;
for ( auto x : v)
cout << x << " " ;
return 0;
}
|
Output
Sorted
9 8 7 6 5 4 3 2 1 0
How to sort in a particular order?
We can also write our own comparator function and pass it as a third parameter.
The comparator function checks, if the statement returned, is true or false and returns a bool value which is passed to the sort function.
For example, lets say Interval i1 = { 6 , 8 } and Interval i2 = { 1, 9 }. When this is passed to the comparator function, it compares i1.start and i2.start. Since, i1.start (=6) < i2.start (=1), the comparator function returns false. This means that Interval i1 should not be placed before Interval i2. Below is the code for this function.
CPP
#include <bits/stdc++.h>
using namespace std;
struct Interval {
int start, end;
};
bool compareInterval(Interval i1, Interval i2)
{
return (i1.start < i2.start);
}
int main()
{
vector<Interval> v { { 6, 8 }, { 1, 9 }, { 2, 4 }, { 4, 7 } };
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
Intervals sorted by start time :
[1, 9] [2, 4] [4, 7] [6, 8]
How to sort the array in descending order based on some parameter using a comparator function?
A comparator function can be passed in such a manner so that the elements in the array get sorted in descending order.
C++
#include <bits/stdc++.h>
using namespace std;
struct Interval {
int start, end;
};
bool compareInterval(Interval i1, Interval i2)
{
return (i1.end > i2.end);
}
int main()
{
vector<Interval> v { { 6, 8 }, { 1, 9 }, { 2, 4 }, { 4, 7 } };
sort(v.begin(), v.end(), compareInterval);
cout << "Intervals sorted by ending time in descending order : \n" ;
for ( auto x : v)
cout << "[" << x.start << ", " << x.end << "] " ;
return 0;
}
|
Output
Intervals sorted by ending time in descending order :
[1, 9] [6, 8] [4, 7] [2, 4]
Related Articles :
Sorting a vector of pairs | Set 1
Sorting a vector of pairs | Set 2
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...