Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Best way to copy members from vector<Class> to vector<Member_Type>

I have a vector of complicated structs (here std::pair<int, int>). I now want to copy a member (say std::pair::first) into a new vector. Is there a better (more idiomatic) way than

std::vector<std::pair<int, int>> list = {{1,2},{2,4},{3,6}};

std::vector<int> x_values;
x_values.reserve(list.size());
for( auto const& elem : list ){
    x_values.emplace_back(elem.first);
}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

std::transform is often used for exactly this:

#include <algorithm>

// ...

std::vector<int> x_values;

std::transform(list.begin(), list.end(), std::back_inserter(x_values), [](auto& pair) {
    return pair.first;
});
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading