Skip to content

Latest commit

 

History

History
80 lines (44 loc) · 3.47 KB

CppExerciseNoForLoopsAnswer22.md

File metadata and controls

80 lines (44 loc) · 3.47 KB

 

 

 

 

 

 

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

 

 

 

 

 

Question #22: CopySecond

 

Replace the for-loop. You will need:

 


#include <vector> ///CopySecond copies the second std::pair elements from a std::vector of std::pairs //From http://www.richelbilderbeek.nl/CppCopySecond.htm template <class T, class U> const std::vector<U> CopySecond(const std::vector<std::pair<T,U> >& v) {   std::vector<U> w;   const int size = static_cast<int>(v.size());   for (int i=0; i!=size; ++i)   {     w.push_back(v[i].second);   }   return w; }

 

 

 

 

 

 

Answer

 


#include <algorithm> #include <vector> #include <boost/lambda/bind.hpp> #include <boost/lambda/lambda.hpp> ///CopySecond copies the second std::pair elements from a std::vector of std::pairs //From http://www.richelbilderbeek.nl/CppCopySecond.htm template <class T, class U> const std::vector<U> CopySecond(const std::vector<std::pair<T,U> >& v) {   std::vector<U> w;   std::transform(     v.begin(),     v.end(),     std::back_inserter(w),     boost::lambda::bind(&std::pair<T,U>::second, boost::lambda::_1)     );   return w; }