Skip to content

Latest commit

 

History

History
98 lines (54 loc) · 5.12 KB

CppExerciseNoForLoopsAnswer31.md

File metadata and controls

98 lines (54 loc) · 5.12 KB

 

 

 

 

 

 

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