Using lambda and find_if expressions in a collection

I have a container object:

R Container;

R is of type list<T*>orvector<T*>

I am trying to write the following function:

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");
}

When trying a method (v is an object of my class)

double f = 1.1;
v.Find(f);

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

I am confused with the lambda expression syntax and what I should write there, and could not find any friendly explanation.

What's wrong? 10x

+3
source share
1 answer

Some context is missing, but I note:

  • You return **itso you can compare*v==itemt
  • You pass const R&vwhere I suspect you meant const T&vin lambda
  • You used const_iterator, but returned a non-constant link. It was a mismatch
  • I made several const & parameters for efficiency (and for supporting non-copyable / non-movable types).

Here is the working code devoid of missing class references:

#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;
}
+6
source

All Articles