💡 퀵 접속: cpp.kr/adjacent_difference

adjacent_difference

C++ 표준 라이브러리의 알고리즘으로, 범위의 각 요소와 그 이전 요소의 차이를 계산합니다. 첫 번째 요소는 그대로 복사됩니다.

기본 사용법

#include <iostream>
#include <vector>
#include <numeric>

int main() {
    std::vector<int> v = {1, 2, 4, 7, 11, 16};
    std::vector<int> result(6);
    
    // 인접 요소 간의 차이 계산
    std::adjacent_difference(v.begin(), v.end(), result.begin());
    
    // 결과 출력
    std::cout << "원본 벡터: ";
    for (int x : v) {
        std::cout << x << " ";
    }
    std::cout << std::endl;
    
    std::cout << "인접 차이: ";
    for (int x : result) {
        std::cout << x << " ";
    }
    std::cout << std::endl;
    
    return 0;
}

실행 결과:

원본 벡터: 1 2 4 7 11 16
인접 차이: 1 1 2 3 4 5

커스텀 연산 사용

#include <iostream>
#include <vector>
#include <numeric>

int main() {
    std::vector<int> v = {1, 2, 4, 7, 11, 16};
    std::vector<int> result(6);
    
    // 인접 요소 간의 비율 계산
    std::adjacent_difference(v.begin(), v.end(), result.begin(),
                           [](int a, int b) { return a / b; });
    
    // 결과 출력
    std::cout << "원본 벡터: ";
    for (int x : v) {
        std::cout << x << " ";
    }
    std::cout << std::endl;
    
    std::cout << "인접 비율: ";
    for (int x : result) {
        std::cout << x << " ";
    }
    std::cout << std::endl;
    
    return 0;
}

실행 결과:

원본 벡터: 1 2 4 7 11 16
인접 비율: 1 2 2 1 1 1

사용자 정의 타입에서 사용

#include <iostream>
#include <vector>
#include <numeric>
#include <string>

struct Point {
    int x, y;
    
    Point operator-(const Point& other) const {
        return {x - other.x, y - other.y};
    }
};

int main() {
    std::vector<Point> points = {
        {1, 2}, {3, 4}, {5, 6}, {7, 8}
    };
    std::vector<Point> result(4);
    
    // 점들 간의 차이 계산
    std::adjacent_difference(points.begin(), points.end(), result.begin());
    
    // 결과 출력
    std::cout << "원본 점들:" << std::endl;
    for (const auto& p : points) {
        std::cout << "(" << p.x << ", " << p.y << ") ";
    }
    std::cout << std::endl;
    
    std::cout << "인접 차이:" << std::endl;
    for (const auto& p : result) {
        std::cout << "(" << p.x << ", " << p.y << ") ";
    }
    std::cout << std::endl;
    
    return 0;
}

실행 결과:

원본 점들:
(1, 2) (3, 4) (5, 6) (7, 8)
인접 차이:
(1, 2) (2, 2) (2, 2) (2, 2)

참고사항

  • adjacent_difference는 numeric 헤더에 정의되어 있습니다.
  • 기본적으로 - 연산자를 사용하여 차이를 계산합니다.
  • 커스텀 연산을 제공할 수 있습니다.
  • 시간 복잡도는 O(n)입니다 (n은 범위의 크기).
  • 결과를 저장할 범위는 충분한 크기여야 합니다.
  • 원본 범위는 수정하지 않습니다.
  • 첫 번째 요소는 그대로 복사됩니다.
함수 설명
adjacent_difference(first, last, result) 기본 - 연산자를 사용하여 인접 요소 간의 차이 계산
adjacent_difference(first, last, result, op) 커스텀 연산을 사용하여 인접 요소 간의 차이 계산