对计算器和主要功能进行更改.
struct Calculator { double operator() ( double result, const Object& obj ) { return result + ( obj.GetA() * obj.GetB()); } }; int main() { std::vector< Object > collection; collection.push_back( Object( 1, 2 ) ); collection.push_back( Object( 3, 4 ) ); double result = std::accumulate( collection.begin(), collection.end(), 0, Calculator() ); std::cout << "result = " << result << std::endl; return 0; }
它也可能更好:
double sumABProduct( double result, const Object& obj ) { return result + ( obj.GetA() * obj.GetB()); } double result = std::accumulate( collection.begin(), collection.end(), 0, sumABProduct );