jeudi 8 juin 2017

Map Filter and Fold in C++

I have a problem that normally would be well suited for Java streams, but I'm currently using c++11.

The way I would solve this problem in java is;

int solution = myList.stream() //myList is an arraylist of MyClass
    .mapToInt(MyClass::GetInt)
    .sum();

After exploring the c++ standard library a little, I have learned that std::transform and std::accumulate exist.

My only problem is that std::transform seems like it can only map from type T to type T, where I need to map from type T to type V (integer), before I can accumulate.

Ideally I'd like to be able to chain this logic together instead of having temporary arrays storing the intermediate results of each step.

Is there an idiomatic c++11 way to accomplish this?

Thanks!

Aucun commentaire:

Enregistrer un commentaire