halivingston halivingston - 1 year ago 64
C++ Question

Initializing a vector<T> using elements from a vector<SuperSetofT> (mapping function?)

class SomeType { int32_t variable; }

std::vector<SomeType> myVector(10);

// ... code to work with myVector

std::vector<int32_t> myOtherVector;
for(int i = 0; i < myVector.size(); i++)

Is there a better way to do this? I've seen how I can use a lambda to do complex initialization, but I can't figure out how to "map" (in C# terms) a Type's certain fields onto this new vector.

Answer Source

It won't be initializing, but you can use std::transform:

std::transform(myVector.cbegin(), myVector.cend(), myOtherVector.begin(), 
               [](auto const& s){
    return s.variable;

or with back_inserter:

myOtherVector.reserve(myVector.size()); // optional
std::transform(myVector.cbegin(), myVector.cend(), std::back_inserter(myOtherVector),
               [](auto const& s){
    return s.variable;

You can initialize it with Boost's transform_iterator:

auto tr = [](auto const& s){
    return s.variable;

vector<int32_t> myOtherVector(
    boost::make_transform_iterator(myVector.begin(), tr),
    boost::make_transform_iterator(myVector.end(), tr)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download