Last Updated: February 25, 2016
·
1.041K
· kybernetyk

functional immutable map in C++11

From time to time you'd like to perform an oldschool lispy map on a std::vector and get a new vector as a result. The problem is that std::transform will mutate your original vector if you don't create an explicit output vector and pass its iterator to std::transform.

IMHO that's a little too much work for every time you want to do a simple map() and so I'v built a little wrapper ...

#include <algorithm>

template <typename T, typename OP>
T map(const T& coll, OP lambda) {
    T new_coll(coll.size());

    std::transform(std::begin(coll),
                   std::end(coll),
                   std::begin(new_coll),
                   lambda);

    return new_coll;
}

void testmap() {
    std::vector<Float32> vec = {1.0, 2.0, 3.0};

    //we could also use a [](const Type&) lambda here
    auto vec2 = map(vec, [](Float32 f) -> Float32 {
        return f * 2.0;
    });

    printf("orig data:\t{");
    for (auto f : vec) {
        printf("%f, ", f);
    }
    printf("}\n new data:\t{");        
    for (auto f : vec2) {
        printf("%f, ", f);
    }
    printf("}\n");
}

Output will be:

orig data:    {1.000000, 2.000000, 3.000000, }
 new data:    {2.000000, 4.000000, 6.000000, }

Have fun ;)