Go back to Richel Bilderbeek's homepage.

Go back to Richel Bilderbeek's C++ page.

 

 

 

 

 

(C++) Answer of exercise #9: No for-loops #28

 

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

 

 

 

 

 

 

Question #28: GetMaxId on std::vector<Person*>

 

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];
}

 

 

 

 

 

 

C++98Boost Answer using C++98 and Boost.Bind

 

#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)));
}

 

 

 

 

 

C++11STL Answer using the C++11 its STL

 

#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(); }
    ));
}

 

 

 

 

 

Go back to Richel Bilderbeek's C++ page.

Go back to Richel Bilderbeek's homepage.

 

Valid XHTML 1.0 Strict