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);
}
std::transform
is often used for exactly this:
#include <algorithm> // transform
#include <iterator> // back_inserter
// ...
std::vector<int> x_values;
x_values.reserve(list.size());
std::transform(list.cbegin(), list.cend(), std::back_inserter(x_values),
[](const auto& pair) { return pair.first; });