Go back to Richel Bilderbeek's homepage.

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

 

 

 

 

 

(C++) Answer of exercise #9: No for-loops #3

 

This is the answer of Exercise #9: No for-loops.

 

 

 

 

 

Question #3: Add

 

Replace the for-loop. You will need:

 

#include <vector>

const std::vector<int> Add(const std::vector<int>& v, const int x)
{
  std::vector<int> v_new(v); //Copy original vector
  const int sz = v.size();
  for (int i=0; i!=sz; ++i)
  {
    v_new[i]+=x;
  }
  return v_new;
}

 

 

 

 

 

Answer

 

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

//From http://www.richelbilderbeek.nl/CppAdd.htm
const std::vector<int> Add(const std::vector<int>& v, const int x)
{
  std::vector<int> v_new;
  std::transform(v.begin(),v.end(),std::back_inserter(v_new),
    std::bind2nd(std::plus<int>(),x));
  return v_new;
}

 

 

 

 

 

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

Go back to Richel Bilderbeek's homepage.

 

Valid XHTML 1.0 Strict