我有一个包含费用的向量。费用是一个结构限制:int ID,float量,字符串类型。我需要按给定金额过滤我的数组。我试图做这样的东西,但它行不通。请帮助我。
<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;
}
和函数getAmount()只需返回费用
最简单(对于您不需要国家保护函数的示例中最简洁的是使用lambda(我假设现在C 11已广泛可用):
std::copy_if(v.begin(),v.end(),std::back_inserter(fil),
[amount](const Expense& e){return e.getAmount() == amount;});
NOTE 您需要使用std::back_inserter
(需要#include <iterator>
)将元素插入矢量fil
,因为您不为此预先分配内存内存。back_inserter
在内部使用push_back
,因此您可以。感谢@juanchopanza指出了这一点。
编辑您的原始代码不起作用,因为您在函数定义后定义了Filter
类,并且后者没有"请参见" Filter
。无论如何,lambda是这里的最佳选择。