std::accumulate
Prerequisites
1. What is std::accumulate?
std::accumulate is a standard algorithm that computes a single accumulated value from a range.
It processes elements sequentially from left to right, combining them using a given operation.
1
2
3
4
5
6
| #include <numeric>
#include <vector>
std::vector<int> v = {1, 2, 3, 4};
int sum = std::accumulate(v.begin(), v.end(), 0);
|
1
| (((init + v[0]) + v[1]) + v[2]) + ...
|
Always evaluated left-to-right
2. Function Signature
1
2
| template<class InputIt, class T>
T accumulate(InputIt first, InputIt last, T init);
|
With Custom Operation
1
2
3
| template<class InputIt, class T, class BinaryOp>
T accumulate(InputIt first, InputIt last,
T init, BinaryOp op);
|
Example: Multiplication
1
2
3
4
5
| int result = std::accumulate(v.begin(), v.end(), 1,
[](int a, int b)
{
return a * b;
});
|
Example: String Concatenation
1
2
3
4
5
6
| #include <string>
#include <vector>
std::vector<std::string> words = {"Hello", " ", "World"};
std::string result = std::accumulate(words.begin(), words.end(), std::string(""));
|
3. Characteristics
3-1. Sequential Execution
- always runs in order
- no parallelism
- deterministic result
3-2. Order Matters
1
2
3
4
5
| std::accumulate(v.begin(), v.end(), 0,
[](int a, int b)
{
return a - b;
});
|
Result depends on order:
```text id=”yl7rxt” (((0 - 1) - 2) - 3) - 4
1
2
3
4
5
6
7
8
|
#### <b>3-3. Initial Value (`init`)</b>
* defines starting value
* affects result type and behavior
```cpp
std::accumulate(v.begin(), v.end(), 100);
|
Result:
4. Common Use Cases
✔️ Sum
```cpp id=”x8drgk” int sum = std::accumulate(v.begin(), v.end(), 0);
1
2
3
4
5
|
##### ✔️ Product
```cpp
int product = std::accumulate(v.begin(), v.end(), 1, std::multiplies<>());
|
✔️ Count with condition
1
2
3
4
5
| int count = std::accumulate(v.begin(), v.end(), 0,
[](int acc, int x)
{
return acc + (x % 2 == 0);
});
|