mardi 29 septembre 2015

Mismatch function passing lambda function as argument

I try to make a list and remove all then just keeping the positive members of it. I want to do it by passing lambda as an argument. I wonder why I get function mismatch error.

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

template<typename T>
std::vector<T> keep(
        const std::vector<T> &original,
        std::function<bool(const T&)> useful)
{
    std::vector<T> out;
    for(T item:original)
    {
        if(useful(item))
            out.push_back(item);
    }
    return out;
}

int main()
{
    std::vector<int> a={4,6,2,-5,3,-8,13,-11,27};
    a=keep(a,[](const int& x)->bool{return x>0;});
    for(int y:a)
    {
        std::cout<<y<<std::endl;
    }
    return 0;
}

And this is the error message:

error: no matching function for call to ‘keep(std::vector<int>&, main():<lambda(const int&)>)’
     a=keep(a,[](const int& x)->bool{return x;});
                                               ^

Aucun commentaire:

Enregistrer un commentaire