Go back to Richel Bilderbeek's homepage.

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

 

 

 

 

 

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

 

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

 

 

 

 

 

Question #27: HasId on std::vector<Person*>

 

Replace the for-loop. You will need:

 

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


bool HasId(const std::vector<const Person *>& v, const int id)
{
  const int size = boost::numeric_cast<int>(v.size());
  for (int i=0; i!=size; ++i)
  {
    if (v[i]->GetId() == id) return true;
  }
  return false;
}

 

 

 

 

 

 

Boost Answer using Boost.Bind

 

#include <algorithm>
#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;
};

bool HasId(const std::vector<const Person *>& v, const int id)
{
  return std::find_if(
    v.begin(),v.end(),
    boost::bind(&Person::GetId, boost::lambda::_1) == id
    ) != v.end();
}

 

 

 

 

 

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

Go back to Richel Bilderbeek's homepage.

 

Valid XHTML 1.0 Strict