(C++) Answer of exercise \#9: No for-loops \#16
January 11, 2018 · View on GitHub
(C++) Answer of exercise #9: No for-loops #16
This is the answer of Exercise #9: No for-loops.
Question #16: Reciprocal
Replace the for-loop. You will need:
#include <vector> void Reciprocal (std::vector<double>& v) { const int sz = static_cast<int>(v.size()); for (int i=0; i!=sz; ++i) { v[i]=1.0/v[i]; } }
Answer
#include <algorithm> #include <numeric> #include <vector> //From http://www.richelbilderbeek.nl/CppReciprocal.htm void Reciprocal (std::vector<double>& v) { std::transform(v.begin(),v.end(),v.begin(), std::bind1st(std::divides<double>(),1.0)); }