[&] { strName = "Terence"; // OK! cout << "Hello " << strName; }; func(); } -------------Output------------ Hello Matthew Auto capture all variables by reference.
[=] Capture any referenced variable by making a copy [=, &foo] Capture any referenced variable by making a copy, but capture variable foo by reference [bar] Capture bar by making a copy; don't copy anything else [this] Capture the this pointer of the enclosing class [x, &y, z ] Capture x, z by making a copy; capture y by reference; don't copy anything else
n; } int main() { vector<int> v { 1, 2, 3, 4, 5 }; cin >> n; for_each( v.begin(), v.end(), plusN ); // print v } -------------Output------------ <= How to get n ??
for each lambda. • Using std::function to wrap lambda, ex: std::function< bool(int) > func = [] ( int i ) -> bool { return i % 2; }; func( 4 ); #include<functional>
typename InputIterator::difference_type len = end - beg; if ( len < 1000 ) return std::accumulate( beg, end, 0 ); InputIterator mid = beg + len / 2; auto handle = std::async( std::launch::async, [&] { parallel_sum( mid, end ); } ); int sum = parallel_sum( beg, mid ); return sum + handle.get(); } int main() { std::vector<int> v(10000, 1); std::cout << "The sum is " << parallel_sum( v.begin(), v.end() ) << '\n'; }