C ++: how to make a "map" of the circuit

The following is an example schema code (correct me if I am wrong):

(define (translate points delta)
    (map 
        (lambda (x)
            (+ x delta)
        )
        points 
    )
)

it basically defines a lambda function that it adds deltafor input x, then applies it to each element points.

I found this feature quite interesting that it omits all iterators, etc.

Is it possible to make such a "map" in C ++ in an elegant way?

Update according to answer:

To be more specific, is there a way to implement such a “map” function of a Schema in C ++ so that it can be used elegantly? Maybe a template function called "map" that takes a function pointer / functor and container?

+4
3

... :

template<typename T, typename F>
T mymap(const T& container, F f) {
    T result;
    for (auto const & x : container) {
        result.push_back(f(x));
    }
    return result;
}

std::vector<int> translate(const std::vector<int>& x, int delta) {
    return mymap(x, [=](int x){return x+delta;});
}

map std::transform, .

++ (, sort , ). , , , .

+1

++ std::transform 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);

lambda - [=]. delta.

T -> T , :

std::vector<point> points{…};

auto lambda = [=](point x) { return x + delta; };
std::transform(begin(points), end(points), begin(points), lambda);
+4

The C ++ version is called std::transform.

+2
source

Source: https://habr.com/ru/post/1569400/


All Articles