320x100
주어진 범위의 데이터를 인자로 넘겨진 계산식으로 계산해 반환한다.
first | 요소 범위의 시작 |
last | 요소 범위의 끝 |
init | 초기 값 |
op | 적용될 한 쌍의 작업 함수 객체 (시그니처: Ret func(const Type1 &a, const Type2 &b); |
#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]), // start with first element
dash_fold);
// Right fold using reverse iterators
std::string rs = std::accumulate(std::next(v.rbegin()), v.rend(),
std::to_string(v.back()), // start with last element
dash_fold);
std::cout << "sum: " << sum << '\n'
<< "product: " << product << '\n'
<< "dash-separated string: " << s << '\n'
<< "dash-separated string (right-folded): " << rs << '\n';
}
Output:
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
https://en.cppreference.com/w/cpp/algorithm/accumulate
https://en.cppreference.com/w/cpp/utility/functional/plus
https://en.cppreference.com/w/cpp/utility/functional/minus
https://en.cppreference.com/w/cpp/utility/functional/multiplies
https://en.cppreference.com/w/cpp/utility/functional/divides
https://en.cppreference.com/w/cpp/utility/functional/modulus
320x100
'프로그래밍 > Morden C++' 카테고리의 다른 글
std::map (0) | 2021.10.05 |
---|---|
std::clamp (0) | 2021.09.29 |
[C++17] std::optional (0) | 2021.07.17 |
std::splice (0) | 2021.07.13 |
std::advance (0) | 2021.07.13 |