Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Building a vector from components contained in another vector type

I have a code that looks something like this:

struct First
{
    int f1;
    int f2;
};

struct Second
{
    First s1;
    int s2;
};

std::vector < Second > secondVec;

Second sec;
sec.s1 = First(); 

secondVec.push_back(sec);
secondVec.push_back(sec);

std::vector < First > firstVec;
firstVec.reserve(secondVec.size());

for (std::vector < Second >::iterator secIter = secondVec.begin(); 
         secIter != = secondVec.end();
         ++secIter)
{
    firstVec.push_back(secIter->s1);
}

I'd like to replace this ugly for loop with a simple stl function that could perhaps perform the equivalent process. I was thinking that maybe std::transform could help me here, but I'm unsure as to how this could be written.

I'd also be interested if boost has anything to offer here.

like image 303
Alan Avatar asked Dec 03 '22 14:12

Alan


1 Answers

If you have TR1 or Boost available, you could try this:

std::transform(secondVec.begin(),
               secondVec.end(),
               std::back_inserter(firstVec),
               std::tr1::bind(&Second::s1, _1));
like image 120
Michael Kristofik Avatar answered Dec 09 '22 16:12

Michael Kristofik