Problem using lambda expressions and auto keyword in C ++

I am trying to learn how to use lambda expressions in C ++.

I tried this simple bit of code, but I get compilation 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 to make the lambda expression an automatic 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 assume these are problems with my compiler, but I'm not quite sure. I just installed MinGW and seems to be using gcc 4.6.2.

+4
source share
1 answer

You must specify the standard option -std=c++0x (for gcc up to version 4.7.0) or -std=c++11 (for gcc version 4.7.0 and later) when compiling code under the new C ++ 11 standard.

+8
source

All Articles