c++のクラスについて
Posted: 2013年1月06日(日) 17:21
クラス型配列の複数の要素にまたがる処理(例えば各要素のメンバごとに平均を求める)を行う場合は、どのようにするのが最も自然なのかを教えてください。お願いします。ちなみに今まではクラスの静的関数を自作して、そこで処理していました。
#include <iostream>
#include <algorithm>
#include <iterator>
class A {
int x_;
public:
A(int x) : x_(x) {}
int get() const { return x_; }
};
int main()
{
const int N = 3;
A x[N] = { A(3), A(4), A(5) };
double average = std::accumulate(std::begin(x), std::end(x), 0.0,
[](double a, const A& b) { return a + b.get(); }) / N;
std::cout << "average = " << average << std::endl;
return 0;
}