algorithm_adjacent_difference
algorithm_adjacent_difference (인접 요소 차이 계산)
std::adjacent_difference는 범위 [first, last)의 인접한 두 요소 사이의 차이를 계산해서 출력 범위에 저장해요. 첫 번째 요소는 그대로 복사되고, 이후 요소는 이전 요소와의 차(또는 이항 연산 결과)가 저장돼요.
출처: cppreference
본문
std::adjacent_difference는 <numeric> 헤더에 정의되어 있어요. T를 decltype(first)의 값 타입이라고 할게요.
template< class InputIt, class OutputIt >
OutputIt adjacent_difference( InputIt first, InputIt last,
OutputIt d_first );
template< class InputIt, class OutputIt, class BinaryOp >
OutputIt adjacent_difference( InputIt first, InputIt last,
OutputIt d_first, BinaryOp op );
- 1번 오버로드 —
[first, last)가 비어 있으면 아무것도 하지 않아요. 그렇지 않으면 다음을 순서대로 수행해요:- 타입
T의 누적기acc를 만들어*first로 초기화해요. acc를*d_first에 할당해요.[++first, last)의 각 반복자iter에 대해 순서대로: 타입T의 객체val을 만들어*iter로 초기화하고val - acc를 계산한 뒤*++d_first에 할당하고val을acc로 복사/이동 할당해요.
- 타입
- 2번 오버로드 —
val - acc대신op(val, acc)를 사용해요 (C++20부터는op(val, std::move(acc))).
매개변수 (Parameters)
first,last— 처리할 요소들의 범위d_first— 출력 범위의 시작policy— 사용할 실행 정책(execution policy)op— 적용할 이항 연산
반환값 (Return value)
마지막으로 쓰여진 요소 다음의 반복자예요. [first, last)가 비어 있으면 d_first를 돌려줘요.
복잡도 (Complexity)
N을 std::distance(first, last)라고 하면 N - 1번의 operator-(또는 op) 적용이 필요해요.
참고 (Notes)
acc는 LWG 이슈 539의 해결로 도입됐어요. 직접 차이를 계산하기보다 acc를 쓰는 이유는 다음 타입들이 어긋날 때 의미가 헷갈리기 때문이에요:
InputIt의 값 타입OutputIt이 쓸 수 있는 타입operator-나op의 매개변수 타입operator-나op의 반환 타입
예제 (Example)
#include <array>
#include <functional>
#include <iostream>
#include <iterator>
#include <numeric>
#include <vector>
void println(auto comment, const auto& sequence)
{
std::cout << comment;
for (const auto& n : sequence)
std::cout << n << ' ';
std::cout << '\n';
}
int main()
{
// Default implementation - the difference between two adjacent items
std::vector v{4, 6, 9, 13, 18, 19, 19, 15, 10};
println("Initially, v = ", v);
std::adjacent_difference(v.begin(), v.end(), v.begin());
println("Modified v = ", v);
// Fibonacci
std::array<int, 10> a {1};
std::adjacent_difference(std::begin(a), std::prev(std::end(a)),
std::next(std::begin(a)), std::plus<>{});
println("Fibonacci, a = ", a);
}
출력:
Initially, v = 4 6 9 13 18 19 19 15 10
Modified v = 4 2 3 4 5 1 0 -4 -5
Fibonacci, a = 1 1 2 3 5 8 13 21 34 55
가능한 구현 (Possible implementation)
template<class InputIt, class OutputIt>
constexpr // since C++20
OutputIt adjacent_difference(InputIt first, InputIt last, OutputIt d_first)
{
if (first == last)
return d_first;
typedef typename std::iterator_traits<InputIt>::value_type value_t;
value_t acc = *first;
*d_first = acc;
while (++first != last)
{
value_t val = *first;
*++d_first = val - std::move(acc); // std::move since C++20
acc = std::move(val);
}
return ++d_first;
}