(C++) ExtractIds
January 7, 2018 · View on GitHub
(C++) ExtractIds
ExtractIds is a container code snippet to extract a certain data type from multiple complex class instances.
ExtractIds extracts the integer called ID from multiple Person class instances stored in a std::vector. Note that the container the Persons are stored in will support the example code below.
#include <algorithm> #include <cassert> #include <vector> #include <boost/lambda/bind.hpp> #include <boost/lambda/lambda.hpp> #include <boost/shared_ptr.hpp> struct Person { Person(const int id) : m_id(id) {} int GetId() const { return m_id; } private: int m_id; }; const std::vector<int> ExtractIds1(const std::vector<Person>& v) { std::vector<int> w; std::transform( v.begin(), v.end(), std::back_inserter(w), boost::lambda::bind(&Person::GetId, boost::lambda::_1) ); return w; } const std::vector<int> ExtractIds2(const std::vector<Person*>& v) { std::vector<int> w; std::transform( v.begin(), v.end(), std::back_inserter(w), boost::lambda::bind(&Person::GetId, boost::lambda::_1) ); return w; } const std::vector<int> ExtractIds3(const std::vector<boost::shared_ptr<Person> >& v) { std::vector<int> w; std::transform( v.begin(), v.end(), std::back_inserter(w), boost::lambda::bind(&Person::GetId, *boost::lambda::_1) //Note the asterisk ); return w; } int main() { { std::vector<Person> v; v.push_back(Person(1)); v.push_back(Person(4)); v.push_back(Person(9)); v.push_back(Person(6)); const std::vector<int> w = ExtractIds1(v); assert(w.size() == 4); assert(w[0] == 1); assert(w[1] == 4); assert(w[2] == 9); assert(w[3] == 6); } { std::vector<Person*> v; v.push_back(new Person(1)); v.push_back(new Person(4)); v.push_back(new Person(9)); v.push_back(new Person(6)); const std::vector<int> w = ExtractIds2(v); assert(w.size() == 4); assert(w[0] == 1); assert(w[1] == 4); assert(w[2] == 9); assert(w[3] == 6); delete v[0]; delete v[1]; delete v[2]; delete v[3]; } { std::vector<boost::shared_ptr<Person> > v; v.push_back(boost::shared_ptr<Person>(new Person(1))); v.push_back(boost::shared_ptr<Person>(new Person(4))); v.push_back(boost::shared_ptr<Person>(new Person(9))); v.push_back(boost::shared_ptr<Person>(new Person(6))); const std::vector<int> w = ExtractIds3(v); assert(w.size() == 4); assert(w[0] == 1); assert(w[1] == 4); assert(w[2] == 9); assert(w[3] == 6); } }