Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Sorting a vector in C++

  • Difficulty Level : Easy
  • Last Updated : 24 Nov, 2021

Prerequisites : std::sort in C++, vector in C++, initialize a vector in C++.
 

Want to learn from the best curated videos and practice problems, check out the C++ Foundation Course for Basic to Advanced C++ and C++ STL Course for foundation plus STL.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

CPP




// C++ program to sort a vector in non-decreasing
// order.
#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 element before.
 

CPP




// C++ program to sort a vector in non-increasing
// order.
#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 particular order? 
We can also write our own comparator function and pass it as a third parameter.
 

CPP




// A C++ program to sort vector using
// our own comparator
#include <bits/stdc++.h>
using namespace std;
 
// An interval has start time and end time
struct Interval {
    int start, end;
};
 
// Compares two intervals according to starting times.
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 the intervals in increasing order 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 : 

Intervals sorted by start time : 
[1, 9] [2, 4] [4, 7] [6, 8] 

Related Articles : 

Sorting a vector of pairs | Set 1 
Sorting a vector of pairs | Set 2
 




My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!