Reputation: 494
I have vector of integers filled with 5 numbers and i'm curious what exactly does [&idx]
do in :
int idx = 0;
for_each ( x . begin (), x . end (), [&idx] ( const int & a ) { cout << idx ++ << " " << a << endl; } );`
Why it does not work like this ? :
int idx = 0;
for_each ( x . begin (), x . end (), ( const int & a, int & idx ) { cout << idx ++ << " " << a << endl; } );
Is it better from perfomance point of view than? :
for ( vector<int>::size_type i = 0; i < x . size (); i ++ )
cout << x[i] << endl;
Upvotes: 1
Views: 199
Reputation: 1819
what exactly does [&idx] do in
the
[](){}
structure, as of C++11, is a lambda function - that is, an anonymous function which, in this context, will be callbacked with the vector elements passed as arguments. The [&idx]
denotes that the variable idx
which DOES NOT NORMALLY BELONG to the lambda's environment and which is NORMALLY INACCESSIBLE by the latter, should be instead accessible (captured) in it by reference. This means that you can use idx
within the body of the lambda and that whenever you do so you are using a reference to the original variable. Therefore, the idx++
part of the code increments the original idx
variable and not some local copy.
Why it does not work like this ?
because () {}
structures are not a valid C++ expressions or statements.
Is it better from perfomance point of view than? :
Probably, but not necessarily, you should measure to find out for sure. However, it is both advisable and idiomatic to use iterators and algorithms rather than C-style loops. Given the standard "avoid premature optimisation" guideline, I suggest that you use the first version by default and when you're done with all development you can decide if you want to dedicate some time to try-out and measure alternatives such as the second. If this is not in some critical part of your program (such as in some callback function), I don't think it deserve the fuss, the difference would be very small anyway.
Just for reference, in my system, using clang++
with -O3
flag, 1000 iterations of your std::foreach
version would last 4967ms while 1000 of the for
one 3861ms. That's approximately 1second for 1000 iterations, e.g. 1ms if you only run this code once..
Upvotes: 3
Reputation: 4637
I'm curious what exactly does
[&idx]
do
That's the lambda capture. It sets the lambda to take a reference to idx
. It won't work as a parameter because for_each
only passes one parameter to the predicate. If you made idx
a parameter instead, it wouldn't compile.
Also is it better from a performance point of view?
Possibly. If you really want to know, test each way of doing it.
Upvotes: 3