std::accumulate
提供: cppreference.com
ヘッダ <numeric> で定義
|
||
(1) | ||
template< class InputIt, class T > T accumulate( InputIt first, InputIt last, T init ); |
(C++20未満) | |
template< class InputIt, class T > constexpr T accumulate( InputIt first, InputIt last, T init ); |
(C++20以上) | |
(2) | ||
template< class InputIt, class T, class BinaryOperation > T accumulate( InputIt first, InputIt last, T init, |
(C++20未満) | |
template< class InputIt, class T, class BinaryOperation > constexpr T accumulate( InputIt first, InputIt last, T init, |
(C++20以上) | |
指定された値 init
と範囲 [first, last)
の要素の合計を計算します。 1つめのバージョンは要素の加算に operator+
を使用し、2つめのバージョンは指定された二項関数 op
を使用します。 どちらの場合も左側の被演算子に std::move が適用されます。 (C++20以上)
|
(C++11未満) |
|
(C++11以上) |
目次 |
[編集] 引数
first, last | - | 加算する要素の範囲 |
init | - | 加算する初期値 |
op | - | 適用される二項演算関数オブジェクト。 二項演算子は現在の累積値 a (init に初期化される) と現在の要素の値 b を取ります。 関数のシグネチャは以下と同等であるべきです。 Ret fun(const Type1 &a, const Type2 &b); シグネチャが const & を持つ必要はありません。 |
型の要件 | ||
-InputIt は LegacyInputIterator の要件を満たさなければなりません。
| ||
-T は CopyAssignable および CopyConstructible の要件を満たさなければなりません。
|
[編集] 戻り値
1) 指定された値と指定された範囲の要素の合計。
[編集] ノート
std::accumulate
は左畳み込みを行います。 右畳み込みを行うためには、二項演算子に渡す引数の順序を反転し、逆イテレータを使用しなければなりません。
[編集] 実装例
1つめのバージョン |
---|
template<class InputIt, class T> constexpr // since C++20 T accumulate(InputIt first, InputIt last, T init) { for (; first != last; ++first) { init = std::move(init) + *first; // C++20以上はstd::move } return init; } |
2つめのバージョン |
template<class InputIt, class T, class BinaryOperation> constexpr // since C++20 T accumulate(InputIt first, InputIt last, T init, BinaryOperation op) { for (; first != last; ++first) { init = op(std::move(init), *first); // C++20以上はstd::move } return init; } |
[編集] 例
Run this code
#include <iostream> #include <vector> #include <numeric> #include <string> #include <functional> 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, std::multiplies<int>()); auto dash_fold = [](std::string a, int b) { return std::move(a) + '-' + std::to_string(b); }; std::string s = std::accumulate(std::next(v.begin()), v.end(), std::to_string(v[0]), // 最初の要素を用いて開始します dash_fold); // 逆イテレータを用いた右畳み込み std::string rs = std::accumulate(std::next(v.rbegin()), v.rend(), std::to_string(v.back()), // 最後の要素を用いて開始します dash_fold); std::cout << "sum: " << sum << '\n' << "product: " << product << '\n' << "dash-separated string: " << s << '\n' << "dash-separated string (right-folded): " << rs << '\n'; }
出力:
sum: 55 product: 3628800 dash-separated string: 1-2-3-4-5-6-7-8-9-10 dash-separated string (right-folded): 10-9-8-7-6-5-4-3-2-1
[編集] 関連項目
指定範囲の隣接する要素間の差を計算します (関数テンプレート) | |
2つの範囲の要素の内積を計算します (関数テンプレート) | |
指定範囲の要素の部分和を計算します (関数テンプレート) | |
(C++17) |
std::accumulate と同様ですが、計算順序は不定です (関数テンプレート) |