sort() in C++ STL

The C++ Standard Library consists of the header, <algorithm> which defines a collection of functions (principally designed to deal with a range of elements). sort() is a function in the STL that sorts a given container (arrays, vectors) in the specified range.

Syntax:

sort(iterator_begin, iterator_end); //sort container ranging from [begin,end)
sort(iterator_begin, iterator_end, comparator); //sort container based on the comparator function 

Parameters: The sort() method accepts 3 parameters:

  • iterator_begin: Random access iterator to initial position
  • iterator_end: Random access iterator to final position ( Note: the range is [iterator_begin,iterator_end) )
  • comparator: Binary function that accepts two elements in the range as arguments, and returns a value convertible to bool. This is used to change the default sorting order.

Return value: none

Example of sort() method

#include <iostream>
#include <algorithm>
#include <vector>

using namespace std;

int main()
{
    vector<int> v;

    v.push_back(5);
    v.push_back(3);
    v.push_back(4);
    v.push_back(2);

    cout<<"Before sorting: \n";
    for( vector<int>::iterator it = v.begin(); it!=v.end(); ++it)
    {
        cout<<*it<<"  ";
    }
    cout<<endl;

    sort(v.begin(),v.end());
    cout<<"Ascending order: \n";
    for( vector<int>::iterator it = v.begin(); it!=v.end(); ++it)
    {
        cout<<*it<<"  ";
    }
    cout<<endl;

    sort(v.begin(),v.end(),greater<int>());
    cout<<"Descending order: \n";
    for( vector<int>::iterator it = v.begin(); it!=v.end(); ++it)
    {
        cout<<*it<<"  ";
    }

}

Output:

Before sorting:
5  3  4  2
Ascending order:
2  3  4  5
Descending order:
5  4  3  2

This article is written by

Please comment below, if you have any doubts or find any error in the above article.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top