0

我不明白为什么这不起作用。我有一个返回std::find方法结果的函数。我读到它返回一个迭代器到它找到的对象。但是当我尝试传递返回该值的 lambda 时,它给了我一堆错误,为什么?

void f(std::function<std::vector<int>::iterator()>) {}

int main()
{
    std::vector<int> v{0, 1, 2, 3};

    auto p = [=] (int n) {
        return std::find(v.begin(), v.end(), n);
    };

    f(p);
}

我得到了很多难以理解的错误。我什至在这里进行了类型检查,结果返回 true:

std::is_same<std::vector<int>::iterator, decltype(std::find(v.begin(), v.end(), N))>::value;
// -> true

f那么,当我将一个函数传递给std::function返回这种类型的函数时,为什么这不起作用呢?

4

3 回答 3

4

假设int参数中缺少的std::function参数是复制粘贴错误,显然是返回sv.begin()而不是普通的迭代器。v.end()const_iterator

这是因为您的 lambda 是按值捕获的,从而生成了您的std::vector const(以及它的迭代器)。通过引用捕获所有内容,否则,您std::function应该返回const_iterator

#include <vector>
#include <functional>
#include <algorithm>

void f(std::function<std::vector<int>::iterator (int)>) {}

int main()
{
    std::vector<int> v{0, 1, 2, 3};

    auto p = [&] (int n) {
        return std::find(v.begin(), v.end(), n);
    };

    f(p);
}
于 2013-01-18T23:03:03.967 回答
2

当您按值捕获时,默认情况下捕获的vector(和关联的迭代器)是const。如果您希望它是可变的,则需要更改 lambda:

auto p = [=] (int n) mutable {
    return std::find(v.begin(), v.end(), n);
};
于 2013-01-18T23:05:05.653 回答
1

因为 f 需要一个不带参数的函数,但是您的 lambda 有一个 int 参数。

于 2013-01-18T22:58:10.590 回答