在 C++ 中使用 Lambda 表达式和 auto 关键字时出现问题

trouble using lambda expressions and auto keyword in c++

本文关键字:关键字 auto 问题 表达式 C++ Lambda      更新时间:2023-10-16

我正在尝试学习如何在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及更高版本)。