【问题标题】:Error using for_each and lambda使用 for_each 和 lambda 时出错
【发布时间】:2017-03-17 06:37:27
【问题描述】:

我正在尝试使用 lambda 函数解决一个简单的斐波那契问题,但我遇到了这个错误,我无法解决。

#include <iostream>
#include <string>
#include <sstream>
#include <vector>
#include <algorithm>


using namespace std;

int main()
{
    string str;
    auto N{0};
    auto i{0};

    cout<<"Digite o valor de N desejado: ";
    getline(cin,str); //pega linha
    stringstream(str) >> N;

    if (N == 0){cout<<0;}
    else if (N == 1){cout<<1;}
    else
    {
        vector<int> v{0,1}; //cria vetor v

        for_each(v.begin(),N,
            [&](){
            v.push_back(v[i]+v[i+1]);
            i++;
        });

        i = 0;

        for_each(v.begin(),N,
            [&](){
            cout<<v[i];
            i++;
            });
    }

    return 0;
}

错误如下:

quest1.cpp: In function ‘int main()’: quest1.cpp:30:4: error: no matching function for call to ‘for_each(std::vector<int>::iterator, int&, main()::<lambda()>)’    });
    ^ In file included from /usr/include/c++/6.3.1/algorithm:62:0,
                 from quest1.cpp:5: /usr/include/c++/6.3.1/bits/stl_algo.h:3763:5: note: candidate: template<class _IIter, class _Funct> _Funct std::for_each(_IIter,
_IIter, _Funct)
     for_each(_InputIterator __first, _InputIterator __last, _Function __f)
     ^~~~~~~~ /usr/include/c++/6.3.1/bits/stl_algo.h:3763:5: note:   template argument deduction/substitution failed: quest1.cpp:30:4: note:   deduced conflicting types for parameter ‘_IIter’ (‘__gnu_cxx::__normal_iterator<int*, std::vector<int> >’ and ‘int’)    });
    ^ quest1.cpp:38:5: error: no matching function for call to ‘for_each(std::vector<int>::iterator, int&, main()::<lambda()>)’
    });
     ^ In file included from /usr/include/c++/6.3.1/algorithm:62:0,
                 from quest1.cpp:5: /usr/include/c++/6.3.1/bits/stl_algo.h:3763:5: note: candidate: template<class _IIter, class _Funct> _Funct std::for_each(_IIter,
_IIter, _Funct)
     for_each(_InputIterator __first, _InputIterator __last, _Function __f)
     ^~~~~~~~ /usr/include/c++/6.3.1/bits/stl_algo.h:3763:5: note:   template argument deduction/substitution failed: quest1.cpp:38:5: note:   deduced conflicting types for parameter ‘_IIter’ (‘__gnu_cxx::__normal_iterator<int*, std::vector<int> >’ and ‘int’)
    });

【问题讨论】:

标签: c++ c++11 lambda


【解决方案1】:

您的代码中有两个问题。一个(已被其他答案涵盖),您将 迭代次数 作为第二个参数传递给 std::for_each,但它实际上需要一个 end 迭代器。 @987654322 @ 旨在从迭代器 a 迭代到迭代器 b 并在该范围内的每个元素上调用 f

第二个问题更为根本:如果在迭代向量时修改向量,您将得到未定义行为,因为任何修改操作都会使向量的所有迭代器无效。

查看您的代码,您似乎希望第一个循环为正常的计数循环,而不是遍历容器。第二个循环可以用 for_each 和一个 lambda 来完成:

vector<int> v{0,1};

for (int i = 0; i < N; ++i) {
  v.push_back(v[i] + v[i+1]);
}

for_each(v.begin(), v.end(),
  [](int element) {
    cout << element;
  }
);

注意for_each 中使用的函子不是空的:算法会将元素传递给它。

或者,打印功能可以在没有 lambda 的情况下实现:

copy(v.begin(), v.end(), ostream_iterator<int>(cout));

或者,如果您希望保留循环,您也可以使用基于范围的for 循环而不是for_each。代码会更短并且[主观]更容易阅读[/主观]:

for (int elem : v) {
  std::cout << elem;
}

【讨论】:

    【解决方案2】:

    std::for_each 需要(正如错误试图告诉您的那样)一个迭代器从哪里开始循环和一个迭代器在哪里结束。但是,您正在传递一个迭代器和一个 int,它们是“冲突类型”。如果您想遍历整个向量,请执行以下操作:

    std::vector<int> v{1, 2, 3};
    std::for_each(v.begin(), // start at the front
                  v.end(),   // loop over each element
                  [&] (int& i) {
                    i++;
                  });
    

    如果您只需要遍历向量的一部分,请执行此操作

    std::vector<int> v{1, 2, 3};
    std::for_each(v.begin(),       // start at the front
                  v.begin() + 2,   // loop over the first two elements
                  [&] (int& i) {
                    i++;
                  });
    

    【讨论】:

      【解决方案3】:

      您没有正确使用for_each 函数。 C++ 不知道您正在使用的签名。请参阅文档,例如for_each.

      编译器就是这么说的。你调用的for_each的第二个参数是int&amp;类型,但是签名是for_each(InputIterator, InputIterator, Function)而不是for_each(InputIterator, int&amp;, Function),所以编译失败。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2020-04-05
        • 1970-01-01
        • 1970-01-01
        • 2023-04-07
        • 1970-01-01
        • 2019-02-25
        • 2021-03-31
        相关资源
        最近更新 更多