Go back to Richel Bilderbeek's homepage.

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

 

 

 

 

 

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

 

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

 

 

 

 

 

Question #1: AddTwo

 

Replace the for-loop. You will need:

 

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

 

 

 

 

 

Answer

 

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

const std::vector<int> AddTwo(const std::vector<int>& v)
{
  std::vector<int> v_new;
  std::transform(v.begin(),v.end(),std::back_inserter(v_new),
    std::bind2nd(std::plus<int>(),2));
  return v_new;
}

 

 

 

 

 

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

Go back to Richel Bilderbeek's homepage.

 

Valid XHTML 1.0 Strict