Tuesday, March 3, 2009

c++ stl - std vector sort (reverse sort)

Example how to sort vector in revers order (C++)
//Author: Darius Kucinskas (c) 2008-2009
//Email: d[dot]kucinskas[eta]gmail[dot]com
//Blog: http://blog-of-darius.blogspot.com/
//License: GPL

#include <algorithm>
#include <vector>
#include <iostream>
#include <iterator>
#include <functional>

int main(int count, char** args)
{
  std::vector<int> v1;
  for(int i=0; i < 10; i++)
  {
    v1.push_back(i);
  }
  
  //sort
  std::cout << "sort" << std::endl;
  std::sort(v1.begin(), v1.end(), std::greater<int>());
  std::copy(v1.begin(), v1.end(), std::ostream_iterator<int>(std::cout, " "));
  std::cout << std::endl;
  
  return 0; 
}
UPDATE Read here how you can sort vector with lambdas in c++0x.