Below is a sample code of Scheme (correct me if i'm wrong):
(define (translate points delta)
(map
(lambda (x)
(+ x delta)
)
points
)
)
basically it defines a lambda function that add delta
to input x
, then apply it to each item of points
.
I found such feature quite interesting that it omits all the iterators and etc.
Is it possible to do such "map" in C++, in an elegant way?
Update according to the reply:
To be more specific, is there a way to implement such "map" function of Scheme, in C++, so that it could be used elegantly? Maybe a template function named "map" that accept function pointer / functor, and a container?
The closest translation of your code in idiomatic C++ would be using std::transform
with a std::back_inserter
:
std::vector<point> points{…};
std::vector<point> output;
// optional, may improve performance:
output.reserve(points.size());
auto lambda = [=](point x) { return x + delta; };
std::transform(begin(points), end(points), std::back_inserter(output), lambda);
Here, lambda
captures its surrounding scope by value – this is indicated by the [=]
prefix. This makes it possible to use delta
inside it.
However, for T -> T
transformations you would usually use an in-place variant instead of pushing values into a new container:
std::vector<point> points{…};
auto lambda = [=](point x) { return x + delta; };
std::transform(begin(points), end(points), begin(points), lambda);
The C++ version is called std::transform
.
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