(C++) Answer of exercise \#9: No for-loops \#26
January 30, 2018 · View on GitHub
(C++) Answer of exercise #9: No for-loops #26
This is the answer of Exercise #9: No for-loops.
Question #26: HasFemale on std::vector<Person*>
Replace the for-loop. You will need:
#include <vector> #include <boost/numeric/conversion/cast.hpp> struct Person { Person(const bool is_male) : m_is_male(is_male) {} bool IsMale() const { return m_is_male; } const bool m_is_male; }; bool HasFemale(const std::vector<const Person *>& v) { const int size = boost::numeric_cast<int>(v.size()); for (int i=0; i!=size; ++i) { if (!v[i]->IsMale()) return true; } return false; }
Answer using Boost.Bind
#include <algorithm> #include <vector> #include <boost/bind.hpp> struct Person { Person(const bool is_male) : m_is_male(is_male) {} bool IsMale() const { return m_is_male; } const bool m_is_male; }; bool HasFemale(const std::vector<const Person *>& v) { return std::find_if( v.begin(),v.end(), std::not1(boost::mem_fn(&Person::IsMale)) ) != v.end(); }