0

I was going through the page of std::for_each_n library function on cppreference std::for_each_n on cppreference.com

I am unable to understand the meaning of "[]" operator (what is it doing there?) in the given context in the example code as mentioned on the webpage. (Kindly look for the commented line in the code below, it is the example as given on the page)

#include <algorithm>
#include <iostream>
#include <vector>
 
int main()
{
    std::vector<int> ns{1, 2, 3, 4, 5};
    for (auto n: ns) std::cout << n << ", ";
    std::cout << '\n';
    std::for_each_n(ns.begin(), 3, [](auto& n){ n *= 2; }); // Line where I have a problem
    for (auto n: ns) std::cout << n << ", ";
    std::cout << '\n';
}

The final argument ([](auto& n) {n *= 2;}) of std::for_each_n is a function definition. What is the meaning of "[]" in this context? I can understand that (auto& n) defines the parameter and in the curly braces is the function logic.

The output of the code FYI is:

1, 2, 3, 4, 5, 
2, 4, 6, 4, 5,
Vishwad
  • 251
  • 3
  • 18

0 Answers0