Sorting using STL Algorithms

Posted in Programming by tux4life on June 23, 2009

After a long hibernation, I’m back with a post on how to use STL Algorithms to sort (virtually anything).

The following code snippet shows how to sort a vector of integers in ascending and descending order.  The same idea can be used to sort a vector, set etc.


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

typedef std::vector<int> IntVector;
void print(const IntVector &);

int main()
IntVector intVector;


//Sort in ascending order
sort(intVector.begin(), intVector.end());

//Sort in descending order
sort(intVector.begin(), intVector.end(), std::greater<int>());

void print(const IntVector &vec)
IntVector::const_iterator itr = vec.begin();
for( ; itr != vec.end(); ++itr )
std::cout << *itr << ” “;

std::cout << std::endl;


Original Vector: 10 13 4 11 2
Sorted Ascending:  2 4 10 11 13
Sorted Descending: 13 11 10 4 2

After inserting few elements into the vector, we can use the “sort” algorithm provided by STL to sort the vector.  The first two arguments are iterations to the starting position and ending position of the vector.

We can also specify the comparison function that is to be used for comparison while sorting.  By default the std::less function object is used.  So the first sort call sorts the vector in ascending order.

To the second sort call, the std::greater function object is used.  So, the vector is sorted in descending order.

There are various function objects available in STL and they can be used as we need them.  You can find a comprehensive list of function objects here.

PS: WordPress is not letting me format the code snippet.  I will find a workaround soon.

Tagged with: , , ,

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: