Code snippets‎ > ‎C++‎ > ‎STL‎ > ‎

Algorithm

This page describes the use of several algorithms defined by the std library.

See also http://www.cplusplus.com/reference/algorithm/.


#include <algorithm>
#include <assert.h>
#include <iostream>
#include <list>
#include <vector>
 
#include <stdlib.h>
 
template<class T> struct print : public std::unary_function<T, void>
{
  print(std::ostream& out) : os(out), count(0) {}
  void operator() (T x) { os << x << ' '; ++count; }
  std::ostream& os;
  int count;
};
 
int main()
{
  /// A C-array
  int A[] = {1, 4, 2, 8, 5, 7};
  const int N = sizeof(A) / sizeof(int);
 
  print<int> P = std::for_each(A, A + N, print<int>(std::cout));
  std::cout << std::endl << P.count << " objects printed." << std::endl;
 
  /// A std::vector
  std::vector<int> V(5);
  fill(V.begin(), V.end(), 1);
 
  std::for_each(V.begin(), V.end(), print<int>(std::cout));
  std::cout << std::endl << P.count << " objects printed." << std::endl;
 
  /// A std::list
  std::list<int> L(V.size());
  std::copy(V.begin(), V.end(), L.begin());
  assert(std::equal(V.begin(), V.end(), L.begin()));
 
  std::for_each(V.begin(), V.end(), print<int>(std::cout));
  std::cout << std::endl << P.count << " objects printed." << std::endl;
}

Comments