-8
void listVsVectorSort(size_t nbr_of_randoms)
{
  std::uniform_int_distribution<int> distribution(0, nbr_of_randoms);
  std::mt19937 engine((unsigned int)time(0)); // Mersenne twister MT19937
  auto generator = std::bind(distribution, engine);
  NumbersInVector  vector(nbr_of_randoms);
  NumbersInList list;

  std::for_each(vector.begin(), vector.end(), [&](Number& n) 
                                              { n = generator(); list.push_back(n); }    );

  TimeValue list_time;
  {  // list measure sort
    g2::StopWatch watch;
    list.sort();
    list_time = watch.elapsedUs().count();
  }

    TimeValue vector_time;    
  {  // vector measure sort
    g2::StopWatch watch;
    std::sort(vector.begin(), vector.end());
    vector_time = watch.elapsedUs().count();
  }

  std::cout <<  nbr_of_randoms << "\t\t, " << list_time << "\t\t, " << vector_time << std::endl;
}

I saw the above code at Code Project. In the line:

std::for_each(vector.begin(), vector.end(), [&](Number& n) 
                                                  { n = generator(); list.push_back(n); }    );

what does [&](Number& n) mean, I am asking more specifically what the [&] means.

Tikky
  • 27
  • 7

3 Answers3

2

It means that everything outside lambda scope will be catch by reference. In that case, generator and list.

1

The [&] is a part of the lambda expression that means it will be able to access all the enclosing variables by reference. Example:

int b = 0;
auto my_lambda = [&](int a) { b = a; };
my_lambda(1);
std::cout << b << '\n'; // prints 1
kirbyfan64sos
  • 9,193
  • 6
  • 51
  • 71
0
[&]

means that all automatic variables will be captured into the scope of the lambda expressing. Essentially, the lambda expression will be able to use the variables that the program had access to at the time of invocation.

Rubix Rechvin
  • 561
  • 3
  • 15