在 C++ 中使用 Lambda 表达式和 auto 关键字时出现问题
trouble using lambda expressions and auto keyword in c++
我正在尝试学习如何在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:mingwbin../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。
在新C++11标准下编译代码时,您必须指定标准选项-std=c++0x
(对于4.7.0版之前的gcc)或-std=c++11
(对于gcc版本4.7.0及更高版本)。
相关文章:
- 考虑到其他好处,关键字'auto'真的有助于简化调试C++吗?
- C++/11 auto 关键字是在更有效时推导参数进行按引用传递,还是始终按值传递?
- auto 关键字在 Dev c++ 中不起作用
- 为什么我需要明确编写"auto"关键字?
- 在C++中使用 auto 关键字
- 在 Objective-C++ 中应用于__weak指针时,通过关键字推导类型"auto"规则是什么?
- 在 VS Code 中编码时不能在 C++ 中使用 auto 关键字
- 避免使用 auto 关键字从字面上复制 const 和非 const 的代码?
- 省略C++可变参数 lambda 中的"auto"关键字?
- 我可以在动态知道其类型的模板类对象中使用 auto 关键字吗?我不能在没有初始值设定项的情况下使用 auto 关键字吗?
- 使用 auto 关键字初始化字符数组
- auto*在编译时有用吗?auto关键字足够了吗
- lambda 中的跨平台"auto"关键字用法:integral_constant作为函数参数
- 使用 C++11 auto 关键字声明两个(或多个)变量
- C++11: "auto"关键字会检索到cv限定符吗?我有矛盾的样本
- 如何在C++中使用关键字"auto"声明和使用变量?
- 非常有用的关键字auto的使用
- 关键字"auto" C++和 C# "dynamic"
- 新关键字"auto" ;什么时候应该使用它来声明变量类型?
- 关键字"auto"接近临界点