(C++) Answer of exercise \#9: No for-loops \#21
January 9, 2018 · View on GitHub
(C++) Answer of exercise #9: No for-loops #21
This is the answer of Exercise #9: No for-loops.
Question #21: CopyFirst
Replace the for-loop. You will need:
#include <vector> ///CopyFirst copies the first std::pair elements from a std::vector of std::pairs //From http://www.richelbilderbeek.nl/CppCopyFirst.htm template <class T, class U> const std::vector<T> CopyFirst(const std::vector<std::pair<T,U> >& v) { std::vector<T> w; const int size = static_cast<int>(v.size()); for (int i=0; i!=size; ++i) { w.push_back(v[i].first); } return w; }
Answer
#include <algorithm> #include <vector> #include <boost/lambda/bind.hpp> #include <boost/lambda/lambda.hpp> ///CopyFirst copies the first std::pair elements from a std::vector of std::pairs //From http://www.richelbilderbeek.nl/CppCopyFirst.htm template <class T, class U> const std::vector<T> CopyFirst(const std::vector<std::pair<T,U> >& v) { std::vector<T> w; std::transform( v.begin(), v.end(), std::back_inserter(w), boost::lambda::bind(&std::pair<T,U>::first, boost::lambda::_1) ); return w; }