💡 퀵 접속: cpp.kr/adjacent_find

adjacent_find

C++ 표준 라이브러리의 알고리즘으로, 주어진 범위에서 연속된 두 요소가 같은 첫 번째 위치를 찾습니다. 기본적으로 == 연산자를 사용하여 비교하며, 커스텀 비교 함수를 제공할 수 있습니다.

기본 사용법

#include <iostream>
#include <vector>
#include <algorithm>

int main() {
    std::vector<int> numbers = {1, 2, 3, 3, 4, 5, 5, 6, 7};
    
    // 연속된 두 요소가 같은 첫 번째 위치 찾기
    auto it = std::adjacent_find(numbers.begin(), numbers.end());
    
    if (it != numbers.end()) {
        std::cout << "연속된 두 요소가 같은 첫 번째 위치를 찾았습니다: " 
                  << std::distance(numbers.begin(), it) << std::endl;
        std::cout << "해당 위치의 값: " << *it << std::endl;
    } else {
        std::cout << "연속된 두 요소가 같은 위치를 찾지 못했습니다." << std::endl;
    }
    
    return 0;
}

실행 결과:

연속된 두 요소가 같은 첫 번째 위치를 찾았습니다: 2
해당 위치의 값: 3

커스텀 비교 함수 사용

#include <iostream>
#include <vector>
#include <algorithm>
#include <cmath>

int main() {
    std::vector<double> numbers = {1.0, 2.0, 2.1, 3.0, 3.1, 4.0, 4.2, 5.0};
    
    // 두 실수가 거의 같은지 비교하는 함수
    auto almost_equal = [](double a, double b) {
        return std::abs(a - b) < 0.2;
    };
    
    auto it = std::adjacent_find(numbers.begin(), numbers.end(), almost_equal);
    
    if (it != numbers.end()) {
        std::cout << "거의 같은 연속된 두 요소의 첫 번째 위치를 찾았습니다: " 
                  << std::distance(numbers.begin(), it) << std::endl;
        std::cout << "해당 위치의 값: " << *it << std::endl;
    } else {
        std::cout << "거의 같은 연속된 두 요소를 찾지 못했습니다." << std::endl;
    }
    
    return 0;
}

실행 결과:

거의 같은 연속된 두 요소의 첫 번째 위치를 찾았습니다: 1
해당 위치의 값: 2

사용자 정의 타입에서 사용

#include <iostream>
#include <vector>
#include <algorithm>
#include <string>

struct Person {
    std::string name;
    int age;
    
    bool operator==(const Person& other) const {
        return name == other.name && age == other.age;
    }
};

int main() {
    std::vector<Person> people = {
        {"Alice", 20},
        {"Bob", 25},
        {"Bob", 25},
        {"Charlie", 30},
        {"David", 35},
        {"David", 35}
    };
    
    // 연속된 두 요소가 같은 첫 번째 위치 찾기
    auto it = std::adjacent_find(people.begin(), people.end());
    
    if (it != people.end()) {
        std::cout << "연속된 두 요소가 같은 첫 번째 위치를 찾았습니다: " 
                  << std::distance(people.begin(), it) << std::endl;
        std::cout << "해당 위치의 값: " << it->name << " (" << it->age << "세)" << std::endl;
    } else {
        std::cout << "연속된 두 요소가 같은 위치를 찾지 못했습니다." << std::endl;
    }
    
    return 0;
}

실행 결과:

연속된 두 요소가 같은 첫 번째 위치를 찾았습니다: 1
해당 위치의 값: Bob (25세)

참고사항

  • adjacent_find는 algorithm 헤더에 정의되어 있습니다.
  • 기본적으로 == 연산자를 사용하여 비교합니다.
  • 커스텀 비교 함수를 제공할 수 있습니다.
  • 시간 복잡도는 O(n)입니다.
  • 연속된 두 요소가 같은 위치를 찾지 못하면 범위의 끝 반복자를 반환합니다.
  • 중복된 요소를 찾거나 연속된 요소의 패턴을 찾는 데 유용합니다.
  • unique 알고리즘과 함께 사용하여 중복을 제거하기 전에 중복된 요소를 찾는 데 사용할 수 있습니다.
함수 설명
adjacent_find(first, last) 기본 비교 연산자를 사용하여 연속된 두 요소가 같은 첫 번째 위치를 찾음
adjacent_find(first, last, binary_pred) 커스텀 비교 함수를 사용하여 연속된 두 요소가 같은 첫 번째 위치를 찾음