This is the answer of Exercise #9: No for-loops.
Replace the for-loop. You will need:
#include <cassert> #include <vector> #include <boost/numeric/conversion/cast.hpp> struct Person { Person(const int id) : m_id(id) {} int GetId() const { return m_id; } const int m_id; }; const Person * GetMaxId(const std::vector<const Person *>& v) { assert(!v.empty()); const int size = boost::numeric_cast<int>(v.size()); int max_id = v[0]->GetId(); int index_max_id = 0; for (int i=1; i!=size; ++i) { const int id = v[i]->GetId(); if (id > max_id) { max_id = id; index_max_id = i; } } return v[index_max_id]; }
#include <algorithm> #include <cassert> #include <vector> #include <boost/bind.hpp> #include <boost/lambda/lambda.hpp> struct Person { Person(const int id) : m_id(id) {} int GetId() const { return m_id; } const int m_id; }; const Person * GetMaxId(const std::vector<const Person *>& v) { return *(std::max_element( v.begin(),v.end(), boost::bind(&Person::GetId,_2) > boost::bind(&Person::GetId,_1))); }
#include <algorithm> #include <vector> struct Person { Person(const int id) : m_id(id) {} int GetId() const { return m_id; } const int m_id; }; const Person * GetMaxId(const std::vector<const Person *>& v) { return *(std::max_element( v.begin(),v.end(), [](const Person* const lhs,const Person* const rhs) { return rhs->GetId() > lhs->GetId(); } )); }