以下代码计算items集合中T的特定属性的平均值:
public double Average<T>(IList<T> items,Func<T,double> selector) { double average = 0.0; for (int i = 0; i < items.Count; i++) { average += selector(items[i]) } return average / items.Count; }
我可以用lambda表达式来调用它:
double average = Average(items,p => p.PropertyName);
我该怎么办?这是我到目前为止
template <typename T> double average(const vector<T>& items,?) { double average= 0.0; for (int i = 0; i < items.size(); i++) { average += ?; } return average/ items.size(); }
我怎么可以用c lambda来调用?
编辑:非常感谢,这里是我最终的结论:
template <typename T> double average(const vector<T>& items,function<double(T)> selector) { double result = 0.0; for (auto i = items.begin(); i != items.end(); i++) { result += selector(*i); } return result / items.size(); }
在main()中:
zombie z1; z1.hit_points = 10; zombie z2; z2.hit_points = 5; items.push_back(z1); items.push_back(z2); double average = average<zombie>(items,[](const zombie& z) { return z.hit_points; });