Non*_*ame -5 c++ arrays stl filter
我有一个包含费用的向量.费用是一个包含的结构:int id,浮动数量,字符串类型.我需要按给定的数量过滤我的数组.我试图做类似的事情,但它不起作用.请帮我.
<Expense> Ctrl::filterbyAmount(vector<Expense>v,float amount){
vector<Expense>fil;
remove_copy_if(v.begin(),v.end(),fil.begin(),Filter(amount));
return fil;
}
class Filter{
Filter(float amount){
this->amount=amount;
}
bool operator()(Expense e){
return(e.getAmount()==amount);
}
private: float amount;
}
Run Code Online (Sandbox Code Playgroud)
而函数getAmount()只返回费用金额
最简单(对于这个不需要状态保存函数的例子,最简洁)是使用lambda(我现在假设C++ 11可以广泛使用):
std::copy_if(v.begin(),v.end(),std::back_inserter(fil),
[amount](const Expense& e){return e.getAmount() == amount;});
Run Code Online (Sandbox Code Playgroud)
注意您需要使用std::back_inserter(需要#include <iterator>)将元素插入向量中fil,因为您没有为其预先分配内存.back_inserter内部使用push_back,所以你会没事的.感谢@juanchopanza指出这一点.
编辑
您的原始代码不起作用,因为您在定义Filter函数后定义了类,因此后者不会"看到" Filter.无论如何,lambda是这里的最佳选择.