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