我正在尝试学习如何在C ++中使用lambda表达式。
我尝试了这个简单的代码,但是我遇到了编译错误:
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;
}
错误:
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)
我也尝试将lambda表达式设为自动变量,但我得到了一组不同的错误。
以下是代码:
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;
}
这给了我以下错误:
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
我假设这些是我的编译器的问题,但我不太确定。
我刚刚安装了MinGW,它似乎正在使用gcc
4.6.2。
答案 0 :(得分:8)
在新C +下编译代码时,您必须指定标准选项-std=c++0x
(适用于版本4.7.0之前的gcc)或-std=c++11
(适用于gcc版本4.7.0及更高版本) +11标准。