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: , , ,

Born Brave

Posted in Uncategorized by tux4life on March 18, 2009

This is one of the most visually descriptive and at the same time factually true pictures that I stumbled upon.. Guess almost everyone would agree 😉

Born Brave

Born Brave

How To Sopcast on Ubuntu

Posted in Ubuntu HowTo's by tux4life on March 18, 2009

Setting up Sopcast in linux can be  bit of a pain.  But recently, I stmbled across a very nice project called sopcast-player hosted in Google Code.  This project offers a GUI based windowed player similar to the Windows version of Sopcast.

The authors are also kind enough to compile the project and give installable packages for various distributions.

Enough said, this is how you install Sopcast on Ubuntu.

Download the package sp-auth_3.0  from here

This package has the script that acts as the streaming server for the video.

Download the package sopcast-player from here

This package has the GUI for the player.

Install both the packages and you are all set.



PS: The authors also provide packages for other architectures and distributions.  You can find it here.