dimanche 27 août 2017

C++11, copying just one field into a vector

Say I have the following struct in C++

struct Foo {
   double a;
   int b;
};

And say I have a parameter to some function declared as follows:

const std::initializer_list<Foo> &args;

Is there an concise way to extract just one field from the elements in args to get, for instance, just an std::vector containing each b field from the original args list?

Of course, I know I could do this by just explicitly writing it out as a loop:

std::vector<int> result;
for(auto &x:args) {
    result.push_back(x.b);
}

... but given that I can copy an entire initializer_list of any type to a like-typed vector just using functions like std::copy and std::back_inserter, I am wondering if there is a more elegant way to do this as well, using stl or C++11 facilities that may already exist.

Aucun commentaire:

Enregistrer un commentaire