💡 퀵 접속: cpp.kr/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(first, last, result) | 기본 - 연산자를 사용하여 인접 요소 간의 차이 계산 |
| adjacent_difference(first, last, result, op) | 커스텀 연산을 사용하여 인접 요소 간의 차이 계산 |