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.
source share