我有一个数字列表。将lambda函数作为参数传递时没有匹配的函数错误
我想过滤列表,只保留正数。
我想通过传递一个lambda作为参数来做到这一点。
我想知道为什么我得到功能不匹配的错误。
#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;
}
这是错误消息:
error: no matching function for call to ‘keep(std::vector<int>&, main()::<lambda(const int&)>)’
a=keep(a,[](const int& x)->bool{return x>0;});
^
您可以使用标准库算法[std :: copy_if](http://en.cppreference.com/w/cpp/algorithm/copy)更轻松地完成此操作:http://coliru.stacked- crooked.com/a/99cdc73f48d19ba7 – Andrew
错误消息中的代码与您的代码不匹配。 – molbdnilo
你用什么编译器? –