在集合上使用lambda表达式和find_if

Mic*_*ael 3 c++ lambda stl

我有一个容器对象:

R Container;
Run Code Online (Sandbox Code Playgroud)

R是类型list<T*>vector<T*>

我正在尝试编写以下函数:

template<typename T, typename R>
T& tContainer_t<T, R>::Find( T const item ) const
{   
typename R::const_iterator it = std::find_if(Container.begin(), Container.end(),  [item](const R&v) { return item == v; });
if (it != Container.end())
    return (**it);
else
    throw Exception("Item not found in container");
}
Run Code Online (Sandbox Code Playgroud)

尝试方法时(v是我班级的对象)

double f = 1.1;
v.Find(f);
Run Code Online (Sandbox Code Playgroud)

我明白了 binary '==' : no operator found which takes a left-hand operand of type 'const double' (or there is no acceptable conversion)

我对lambda表达式语法和我应该在那里写的东西感到困惑,并且找不到任何友好的解释.

怎么了 ?10X.

seh*_*ehe 6

缺少一些背景,但我注意到:

  • 你返回**it所以你可能想要比较*v==itemt
  • 你经过const R&v我怀疑你想const T&v进入lambda的地方
  • 您使用了const_iterator,但返回了非const引用.那是不匹配的
  • 为了效率,我制作了一些常量const(并支持不可复制/不可移动的类型)

这是工作代码,删除了缺少的类引用:

#include <vector>
#include <algorithm>
#include <iostream>

template<typename T, typename R=std::vector<T> >
T& Find(R& Container, T const& item ) 
{   
    typename R::iterator it = std::find_if(Container.begin(), Container.end(),  [&item](const T&v) { return item == v; });
    if (it != Container.end())
        return *it;
    else
        throw "TODO implement";
}

int main(int argc, const char *argv[])
{
    std::vector<double> v { 0, 1, 2, 3 };
    Find(v, 2.0); // not '2', but '2.0' !
    return 0;
}
Run Code Online (Sandbox Code Playgroud)