dridk dridk - 1 month ago 11
C++ Question

How to make a C++ intention list

I would like to make an intention list like python does.

list = [1,2,3,4]
newList = [ i * 2 for i in list ] 


Using std,iterator and lambda function, it should be possible to do the same things in one line.

std::vector<int> list = {1,2,3,4} ;
std::vector<int> newList =


Could you complete it ?

Answer

std::transform lets you transform values and put them somewhere else:

std::vector<int> list = {1,2,3,4};
std::vector<int> newList;

std::transform(
    list.cbegin(),
    list.cend(),
    back_inserter(newList),
    [](int x) { return x * 2; });

But really, C++ is not the language for conciseness.