2

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!

2
  • not worth to add another answer, but I'd like to add that in the following like you can find a possible implementation of for_each where you can see how the lamda is called. Note that the implementation is the same, whether you pass a lambda, function pointer or any other callable. en.cppreference.com/w/cpp/algorithm/for_each Commented Mar 23, 2020 at 15:33
  • ... just realized that Francois already provided the same link below ;) Commented Mar 23, 2020 at 15:35

3 Answers 3

7

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.)

Sign up to request clarification or add additional context in comments.

1 Comment

Maybe an possible implementation of for_each would also help. It shows that foo is called in a for loop with an argument.
2

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.

Comments

1

n doesn't point a thing. the algorithm iterates over the container and uses each element in it (by dereferencing the iterators) as an argument for the lambda.

See https://en.cppreference.com/w/cpp/algorithm/for_each

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.