Go back to Richel Bilderbeek's homepage.

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

 

 

 

 

 

(C++) Halve

 

 

Halve is a container code snippet to replace all values in a container by their halves (that is: x/2.0).

 

There are multiple ways to perform Halve:

 

 

 

 

 

The general algorithm way

 

#include <algorithm>
#include <numeric>

//From http://www.richelbilderbeek.nl/CppHalve.htm
template <class Container>
void Halve(Container& c)
{
  std::transform(c.begin(),c.end(),c.begin(),
    std::bind2nd(std::divides<Container::value_type>(),2.0));    
}

 

 

 

 

 

The algorithm way on a std::vector<double>

 

This way is used as an answer in Exercise #9: No for-loops.

 

#include <vector>
#include <algorithm>
#include <numeric>

//From http://www.richelbilderbeek.nl/CppHalve.htm
void Halve(std::vector<double>& v)
{
  std::transform(v.begin(),v.end(),v.begin(),
    std::bind2nd(std::divides<double>(),2.0));    
}

 

 

 

 

 

Thefor-loop way on a std::vector<double>

 

Prefer algorithms over loops [1,2].

 

#include <vector>

//From http://www.richelbilderbeek.nl/CppHalve.htm
void Halve(std::vector<double>& v)
{
  const int sz = v.size();
  for (int i=0; i!=sz; ++i)
  {
    v[i]/=2.0;
  }
}

 

 

 

 

 

References

 

  1. Bjarne Stroustrup. The C++ Programming Language (3rd edition). ISBN: 0-201-88954-4. Chapter 18.12.1 : 'Prefer algorithms over loops'
  2. Herb Sutter and Andrei Alexandrescu. C++ coding standards: 101 rules, guidelines, and best practices. ISBN: 0-32-111358-6. Chapter 84: 'Prefer algorithm calls to handwritten loops.'

 

 

 

 

 

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

Go back to Richel Bilderbeek's homepage.

 

Valid XHTML 1.0 Strict