trouble using lambda expressions and auto keyword in c++
auto, c++, c++11, lambda, mingw
Solution
You have to specify the standard option `-std=c++0x` (for gcc prior to version 4.7.0) or `-std=c++11` (for gcc version 4.7.0 and later) when compiling the code under the new C++11 standard.
Problem
I'm trying to learn how to use lambda expressions in C++. I tried this simple bit of code but I get compile errors: ``` int main() { vector<int> vec; for(int i = 1; i<10; i++) { vec.push_back(i); } for_each(vec.begin(),vec.end(),[](int n){cout << n << " ";}); cout << endl; } ``` Errors: ``` forEachTests.cpp:20:61: error: no matching function for call to'for_each(std::vector<int>::iterator, std::vector<int>::iterator, main()::<lambda(int)>)' forEachTests.cpp:20:61: note: candidate is: c:\mingw\bin\../lib/gcc/mingw32/4.6.2/include/c++/bits/stl_algo.h:4373:5: note:template<class _IIter, class _Funct> _Funct std::for_each(_IIter, _IIter, _Funct) ``` I also tried making the lambda expression an auto variable but I got a different set of errors. Here is the code: ``` int main() { vector<int> vec; for(int i = 1; i<10; i++) { vec.push_back(i); } auto print = [](int n){cout << n << " ";}; for_each(vec.begin(),vec.end(),print); cout << endl; } ``` This gave me the following errors: ``` forEachTests.cpp: In function 'int main()': forEachTests.cpp:20:7: error: 'print' does not name a type forEachTests.cpp:22:33: error: 'print' was not declared in this scope ``` I'm assuming these are problems with my compiler but I am not quite sure. I just installed MinGW and it appears to be using `gcc` 4.6.2.