Go back to Richel Bilderbeek's homepage.

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

 

 

 

 

 

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

 

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

 

 

 

 

 

Question #31: Find an ID in a std::vector<const Person*>

 

Replace the for-loop. You will need:

 

#include <algorithm>
#include <vector>

struct Id
{
  Id(const int id) : m_id(id) { }
  int Get() const { return m_id; }
  private:
  int m_id;
};

struct Person
{
  Person(const int id) : m_id(new Id(id)) {}
  const Id * GetId() const { return m_id.get(); }
  private:
  boost::scoped_ptr<Id> m_id;
};

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

 

 

 

 

 

Boost Answer using Boost.Bind

 

#include <algorithm>
#include <vector>
#include <boost/bind.hpp>
#include <boost/lambda/bind.hpp>
#include <boost/scoped_ptr.hpp>

struct Id
{
  Id(const int id) : m_id(id) { }
  int Get() const { return m_id; }
  private:
  int m_id;
};

struct Person
{
  Person(const int id) : m_id(new Id(id)) {}
  const Id * GetId() const { return m_id.get(); }
  private:
  boost::scoped_ptr<Id> m_id;
};

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

 

 

 

 

 

FAILCpp11 Failed attempt using C++11

 

Sadly, this does not work and I do not understand why yet...

 

bool IsIdTaken(const std::vector<const Person*>& v, const int id)
{
  return std::find_if(
    v.begin(),v.end(),
      [id](const Person * person) { person->GetId()->Get() == id; }
    ) != v.end();
}

 

 

 

 

 

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

Go back to Richel Bilderbeek's homepage.

 

Valid XHTML 1.0 Strict