std::accumulate
出自cppreference.com
| 在標頭 <numeric> 定義
|
||
| (1) | (C++20 起為 constexpr) |
|
| (2) | (C++20 起為 constexpr) |
|
計算給定值 init 與範圍 [first, last) 中各元素的和。
1) 以初始值
init 初始化(具有 T 類型的)累加器 acc,然後按順序對範圍 [first, last) 的每個迭代器 i 通過 acc = acc + *i(C++20 前)acc = std::move(acc) + *i(C++20 起) 進行累加。2) 以初始值
init 初始化(具有 T 類型的)累加器 acc,然後按順序對範圍 [first, last) 的每個迭代器 i 通過 acc = op(acc, *i)(C++20 前)acc = op(std::move(acc), *i)(C++20 起) 進行累加。如果滿足以下任意條件,那麼行為未定義:
T不可複製構造 (CopyConstructible) 。T不可複製賦值 (CopyAssignable) 。op會修改[first,last)的任何元素。op會使[first,last]中的任何迭代器或子範圍失效。
參數
| first, last | - | 要累加的元素範圍的迭代器對 |
| init | - | 累加的初值 |
| op | - | 被使用的二元函數對象。 該函數的簽名應當等價於:
簽名中並不需要有 |
| 類型要求 | ||
-InputIt 必須滿足老式輸入迭代器 (LegacyInputIterator) 。
| ||
返回值
所有修改完成後的 acc。
可能的實現
| accumulate (1) |
|---|
template<class InputIt, class T>
constexpr // 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;
}
|
| accumulate (2) |
template<class InputIt, class T, class BinaryOperation>
constexpr // 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;
}
|
註解
std::accumulate 進行左摺疊。為進行右摺疊,必須逆轉二元運算符的實參順序,並使用逆序迭代器。
如果使用類型推導,那麼 op 就會對與 init 相同類型的值進行操作,這可能引入對迭代器元素非預期的轉型,例如 std::accumulate(v.begin(), v.end(), 0) 在 v 是 std::vector<double> 時會給出錯誤的結果。
示例
運行此代碼
#include <functional>
#include <iostream>
#include <numeric>
#include <string>
#include <vector>
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 << '\n'
<< "积:" << product << '\n'
<< "以短横线分隔的字符串:" << s << '\n'
<< "以短横线分隔的字符串(右折叠):" << rs << '\n';
}
輸出:
和:55
积:3628800
以短横线分隔的字符串:1-2-3-4-5-6-7-8-9-10
以短横线分隔的字符串(右折叠):10-9-8-7-6-5-4-3-2-1
缺陷報告
下列更改行為的缺陷報告追溯地應用於以前出版的 C++ 標準。
| 缺陷報告 | 應用於 | 出版時的行為 | 正確行為 |
|---|---|---|---|
| LWG 242 | C++98 | op 不能有任何副作用
|
它不能修改涉及到的範圍 |
參閱
| 計算範圍中相鄰元素的差 (函數模板) | |
| 計算兩個範圍中元素的內積 (函數模板) | |
| 計算範圍中元素的部分和 (函數模板) | |
(C++17) |
類似 std::accumulate,但不依序執行 (函數模板) |
(C++23) |
左摺疊範圍中元素 (算法函數對象) |