/
Blog
/
Programming
/
C++
/
numeric
accumulate#
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); // std::move since C++11
return init;
}
각 원소 대상으로 뭔가를 적용해서 누적한 결과를 하나(op의 리턴타입)로 리턴하는 함수이다.
init과 리턴값은 타입이 같다. (0.f, 0L 등으로 타입도 지정가능)
op가 전달되지 않으면 덧셈 함수가 전달된다.
BinaryOperator 는 첫번째 인자에 init이 전달돼서 각 원소를 처리한 데이터가 쌓인다.
std:: string dash_fold = [](std:: string a, int b)
{
return std:: move(a) + '-' + std:: to_string(b);
};
// ret: 1-2-3-4-5-6-7-8-9-10
adjacent_difference#
template < class InputIt , class OutputIt , class BinaryOperation >
constexpr // since C++20
OutputIt adjacent_difference(InputIt first, InputIt last,
OutputIt d_first, BinaryOperation op)
{
if (first == last)
return d_first;
typedef typename std:: iterator_traits< InputIt>:: value_type value_t;
value_t acc = * first; // 첫번째 값
* d_first = acc; // output의 첫배열에 저장
while (++ first != last)
{
value_t val = * first;
*++ d_first = op(val, std:: move(acc)); // std::move since C++11
acc = std:: move(val);
}
return ++ d_first;
}
인접한 두 요소에 뭔가를 적용한 값을 배열형태(꼭 배열이여야 하는건 아님)로 리턴하는 함수이다.
리턴되는 배열의 첫 원소는 input 배열의 첫번째 데이터이다.
op에 전달되는 인자는 배열의 순서상 (n+1, n) 인덱스의 데이터로 전달된다.
op가 전달되지 않으면 두 수의 차이(a-b)가 리턴되는 함수가 적용된다.
int print_value = [](int a, int b) {
std:: cout << a << " / " << b << std:: endl;
return a;
}
/*
2 / 1
3 / 2
6 / 3
5 / 6
ret_arr: 1 2 3 6 5
*/
iota#
template < class ForwardIt , class T >
constexpr // since C++20
void iota(ForwardIt first, ForwardIt last, T value)
{
while (first != last)
{
* first++ = value;
++ value;
}
}
first부터 last까지 value를 하나씩 증가시켜서 저장한다.
← Previous
c++ 컴파일 표준과 구현체
Next →
모던 c++ 문법
Comments