template<classInputIt, classT, classBinaryOperation>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<classInputIt, classOutputIt, classBinaryOperation>constexpr// since C++20
OutputIt adjacent_difference(InputIt first, InputIt last,
OutputIt d_first, BinaryOperation op)
{
if (first == last)
return d_first;
typedeftypename 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<classForwardIt, classT>constexpr// since C++20
void iota(ForwardIt first, ForwardIt last, T value)
{
while (first != last)
{
*first++= value;
++value;
}
}
Comments