Search code examples
c++algorithmcopystdvectorstd

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

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