The Wayback Machine - https://web.archive.org/web/20180426122421/http://ja.cppreference.com:80/w/cpp/algorithm/accumulate
名前空間
変種
操作

std::accumulate

提供: cppreference.com
< cpp‎ | algorithm

 
 
アルゴリズムライブラリ
実行ポリシー (C++17)
非変更シーケンス操作
(C++11)(C++11)(C++11)
(C++17)
変更シーケンス操作
未初期化記憶域の操作
分割操作
ソート操作
バイナリサーチ操作
集合操作 (ソート済み範囲に対する)
ヒープ操作
(C++11)
最小/最大演算
(C++11)
(C++17)
順列
数値演算
accumulate
(C++17)
C のライブラリ
 
ヘッダ <numeric> で定義
template<class InputIt, class T >
T accumulate( InputIt first, InputIt last, T init );
(1)
template<class InputIt, class T, class BinaryOperation >

T accumulate( InputIt first, InputIt last, T init,

              BinaryOperation op );
(2)

Computes the sum of the given value init and the elements in the range [first, last). The first version uses operator+ to sum up the elements, the second version uses the given binary function op.

目次

[編集]パラメータ

first, last -
和への要素の範囲
Original:
the range of elements to sum
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
init - initial value of the sum
op - binary operation function object that will be applied.

The signature of the function should be equivalent to the following:

 Ret fun(const Type1 &a, const Type2 &b);

The signature does not need to have const&.
Type1 は、 T 型のオブジェクトから暗黙に変換可能なものでなければなりません。 型 Type2 は、 InputIt 型のオブジェクトの逆参照から暗黙に変換可能なものでなければなりません。 The type Ret must be such that an object of type T can be assigned a value of type Ret. ​

型の要件
-
InputItInputIterator の要件を満たさなければなりません。
-
TCopyAssignable および CopyConstructible の要件を満たさなければなりません。

[編集]値を返します

The sum of the given value and elements in the given range.

[編集]可能な実装

1つめのバージョン
template<class InputIt, class T> T accumulate(InputIt first, InputIt last, T value){for(; first != last;++first){ value = value +*first;}return value;}
2つめのバージョン
template<class InputIt, class T, class BinaryOperation> T accumulate(InputIt first, InputIt last, T value, BinaryOperation op){for(; first != last;++first){ value = op(value, *first);}return value;}

[編集]

#include <iostream>#include <vector>#include <numeric>#include <string>   int multiply(int x, int y){return x*y;}   std::string magic_function(std::string res, int x){return res +=(x >5)?"b":"s";}   int main(){std::vector<int> v{1, 2, 3, 4, 5, 6, 7, 8, 9, 10};   int sum = std::accumulate(v.begin(), v.end(), 0);int product = std::accumulate(v.begin(), v.end(), 1, multiply);std::string magic = std::accumulate(v.begin(), v.end(), std::string(), magic_function);   std::cout<< sum <<'\n'<< product <<'\n'<< magic <<'\n';}

出力:

55 3628800 sssssbbbbb

[編集]参照

指定範囲の隣接する要素間の差を計算します
(関数テンプレート)[edit]
2つの範囲の要素の内積を計算します
(関数テンプレート)[edit]
指定範囲の要素の部分和を計算します
(関数テンプレート)[edit]
close