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.
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.
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.
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.
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.
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;});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With