Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Equivalent of python map function using lambda

I am wondering if it is possible to write a C++ equivalent of the Python function map, using the automatic return type deduction feature. What I have in mind is something like this:

vector<int> input({1,2,3});
auto output=apply(input,[](int num){return num*num;});

//output should be a vector {1,4,9}

I do know about std::transform, but in the present state of affairs, writing a range loop seems easier.

like image 474
SPMP Avatar asked Oct 27 '15 21:10

SPMP


People also ask

What is the equivalent of map in Python?

Map in Python is a function that works as an iterator to return a result after applying a function to every item of an iterable (tuple, lists, etc.). It is used when you want to apply a single transformation function to all the iterable elements. The iterable and function are passed as arguments to the map in Python.

What is map in lambda?

The map() function in Python takes in a function and a list as an argument. The function is called with a lambda function and a list and a new list is returned which contains all the lambda modified items returned by that function for each item.

Does Python have a map function?

Python's map() is a built-in function that allows you to process and transform all the items in an iterable without using an explicit for loop, a technique commonly known as mapping. map() is useful when you need to apply a transformation function to each item in an iterable and transform them into a new iterable.

What can I use instead of lambda in Python?

One of good alternatives of lambda function is list comprehension. For map() , filter() and reduce() , all of them can be done using list comprehension. List comprehension is a solution between a regular for-loop and lambda function.


1 Answers

This has already been discussed in comments, but I think it should also be given as an answer: The function std::transform from <algorithm> does what you want.

The following code works for me:

#include <vector>
#include <algorithm>
using namespace std;

//...

vector<int> input({1,2,3});
transform(input.begin(), input.end(), input.begin(), [](int num){return num*num;});
like image 135
lhk Avatar answered Sep 27 '22 19:09

lhk