std::accumulate

提供: C++入門
移動: 案内検索
スポンサーリンク


読み方

std::accumulate
えすてぃーでぃー あきゅむれーと

概要

std::accumulate は、配列の値の総和を求めたり、関数オブジェクトを用いることで、和以外の計算を簡単に行えます。

accumulate の意味は、以下の通りです。

他動
積み上げる、蓄積する、集める
自動
ふえる、積もる、集まる

合計を求める例

ソースコード std_accumulate_sum_1.cpp

#include <iostream>
#include <boost/foreach.hpp>
#include <vector>
#include <numeric>
 
using namespace std;
 
void
dump(vector<int>& v)
{
        BOOST_FOREACH(int x, v) {
                cout << x << endl;
        }
}
 
int
main (int argc, char *argv[])
{
        vector<int> v;
 
        v.push_back ( 3 );
        v.push_back ( 4 );
        v.push_back ( 1 );
        v.push_back ( 2 );
 
        cout << "Value" << std::endl;
        dump (v);
 
        int sum = std::accumulate(v.begin(), v.end(), 0 );
 
        cout << "Sum" << std::endl;
        cout << sum << std::endl;
        return 0;
}

コンパイル

g++  -I/usr/local/include std_accumulate_sum_1.cpp -o std_accumulate_sum_1

実行例

% ./std_accumulate_sum_1
Value
3
4
1
2
Sum
10

関数オブジェクトを利用して総乗を求める例

ソースコード std_accumulate_function_object.cpp

#include <iostream>
#include <boost/foreach.hpp>
#include <vector>
#include <numeric>
 
using namespace std;
 
void
dump(vector<int>& v)
{
        BOOST_FOREACH(int x, v) {
                cout << x << endl;
        }
}
 
class Multiply {
        public:
                int operator() (const int sum, const int value) {
                        return sum * value;
                }
};
 
int
main (int argc, char *argv[])
{
        vector<int> v;
 
        v.push_back ( 3 );
        v.push_back ( 4 );
        v.push_back ( 1 );
        v.push_back ( 2 );
 
        cout << "Value" << std::endl;
        dump (v);
 
        int sum = std::accumulate(v.begin(), v.end(), 1, Multiply() );
 
        cout << "Multiply" << std::endl;
        cout << sum << std::endl;
        return 0;
}

コンパイル

g++  -I/usr/local/include std_accumulate_function_object.cpp -o std_accumulate_function_object

実行例

% ./std_accumulate_function_object
Value
3
4
1
2
Multiply
24

関連項目




スポンサーリンク