Go back to Richel Bilderbeek's homepage.

Go back to Richel Bilderbeek's C++ page.

 

 

 

 

 

(C++) SortVector

 

SortVector is a sorting code snippet to sort a container.

 

#include <algorithm>
#include <iostream>
#include <vector>
#include <boost/foreach.hpp>

//From http://www.richelbilderbeek.nl/CppSortVector.htm
template <class T>
T SortVector(const T& v)
{
  T w(v);
  std::sort(w.begin(),w.end());
  return w;
}

int main()
{
  //Create a std::vector with five random values
  std::vector<int> v;
  for (int i=0; i!=5; ++i) v.push_back(std::rand() % 100);

  //Display the std::vector
  BOOST_FOREACH(const int i, v) std::cout << i << " ";
  std::cout << '\n';

  const std::vector<int> w(SortVector(v));
  BOOST_FOREACH(const int i, w) std::cout << i << " ";
  std::cout << '\n';
}

 

Screen output:

 

83 86 77 15 93
15 77 83 86 93

 

 

 

 

 

Go back to Richel Bilderbeek's C++ page.

Go back to Richel Bilderbeek's homepage.

 

Valid XHTML 1.0 Strict