How do STD Algorithms handle the lambda pointer?

Viewed 86

so I'm using this small function to print a vector. It works but I'm trying to understand how it works:

 void const print_vector(vector<int> const& v)
{
    std::for_each(v.begin(), v.end(), [](const int& n) {std::cout << n << " ";});
}

How does the "n" variable know to point to the element of the vector?

Any further corrections are appreciated as well

Thank you!

3 Answers

Your code is equivalent to this:

void const print_vector(vector<int> const& v)
{
    std::for_each(v.begin(), v.end(), foo);
}

void foo(const int& n) 
{ 
    std::cout << n << " "; 
}

Your lambda is just a shorthand way of declaring the function foo.

The address of foo is then passed into for_each.

for_each loops through the vector and calls foo each time, passing in the current element as the parameter n.

(Note: it's not exactly equivalent. The lambda is actually a functor, not a function, but that just confuses matters and makes no difference here.)

How does the "n" variable know to point to the element of the vector?

n is just an argument of the functor. It is a reference, and it refers to whatever object is passed as an argument to the functor when it is called. std::for_each is what calls the functor and passes the argument.

std::for_each on the other hand knows to "point" to the element because you passed the begin and end iterators pointing to the vector into it as arguments. std::for_each indirects through the begin iterator to get the first element, calls the functor and passes the result of the indirection as an argument. Then std::for_each increments the iterator and repeats until the entire range has been iterated.

Related