I don’t understand why this isn’t working. I have a function that returns the result of the std::find method. I read that it returns an iterator to object it finds. But when I try passing the lambda that returns that value it gives me a bunch of errors, why?
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);
}
I get a lot of incomprehensible errors. I even did a type check here and it returned true:
std::is_same<std::vector<int>::iterator, decltype(std::find(v.begin(), v.end(), N))>::value;
// -> true
So why doesn’t this work when I pass a function to f with std::function that returns this type?
Assuming the
intparameter missing in yourstd::functionparameter was a copy-paste mistake, apparentlyv.begin()andv.end()returnconst_iterators rather than normal iterators.This is due to the fact that your lambda was capturing by value, making your
std::vectorconst(and thus its iterators). Capturing everything by reference works, otherwise, yourstd::functionshould return aconst_iterator: