スキップしてメイン コンテンツに移動

C++: STLコンテナの数値の和、積および二乗の和を求める

vectorクラスやlistクラスなどのSTLコンテナで数値リストの和や積をともめる場合、numericのaccumulateを使う。積などの関数オブジェクトを利用する場合はfunctionalも使う。二乗の和の求め方も示す。

#include <iostream> #include <vector> #include <numeric> #include <functional> using namespace std; // 二乗の和の関数オブジェクト. template<class T> class add_square : public binary_function<T, T, T> { public: result_type operator()(first_argument_type a, second_argument_type b) { return a + b * b; } }; int main() { vector<int> v(5, 3); // 数値3が5つ入ったvectorクラス. // 和. cout << "3 + 3 + 3 + 3 + 3 = "; cout << accumulate(v.begin(), v.end(), 0) << endl; // 積. cout << "3 * 3 * 3 * 3 * 3 = "; cout << accumulate(v.begin(), v.end(), 1, multiplies<int>()) << endl; // 二乗の和. cout << "3^2 + 3^2 + 3^2 + 3^2 + 3^2 = "; cout << accumulate(v.begin(), v.end(), 0, add_square<int>()) << endl; return 0; }

以下のように表示される。

3 + 3 + 3 + 3 + 3 = 15 3 * 3 * 3 * 3 * 3 = 243 3^2 + 3^2 + 3^2 + 3^2 + 3^2 = 45

因みに、二乗の和では関数オブジェクトを使わずに以下のように内積を求めるinner_productでも同じ結果を得ることができる。ただし、三乗の和や対数の積など、任意の計算をしたい場合は、素直に関数オブジェクト作成してaccumulateを利用した方がスマートだと思う。

inner_product(v.begin(), v.end(), v.begin(), 0);

コメント