Namespaces
Variants

std::adjacent_find

cppreference.net에서
 
 
알고리즘 라이브러리
제한된 알고리즘 및 범위 기반 알고리즘 (C++20)
제한된 알고리즘, 예: ranges::copy, ranges::sort, ...
정렬 및 관련 연산
분할 연산
(C++11)    

정렬 연산
이진 탐색 연산
(분할된 범위에서)
집합 연산 (정렬된 범위에서)
병합 연산 (정렬된 범위에서)
힙 연산
최소/최대 연산
(C++11)
(C++17)
사전식 비교 연산
순열 연산


 
헤더 <algorithm>
template< class ForwardIt >
ForwardIt adjacent_find( ForwardIt first, ForwardIt last );
에 정의됨 (1) (C++20부터 constexpr)
template< class ForwardIt, class BinaryPred >
ForwardIt adjacent_find( ForwardIt first, ForwardIt last,
                         BinaryPred p );
(2) (C++20부터 constexpr)
template< class ExecutionPolicy, class ForwardIt >
ForwardIt adjacent_find( ExecutionPolicy&& policy,
                         ForwardIt first, ForwardIt last );
(3) (C++17부터)
template< class ExecutionPolicy, class ForwardIt, class BinaryPred >
ForwardIt adjacent_find( ExecutionPolicy&& policy,
                         ForwardIt first, ForwardIt last,
                         BinaryPred p );
(4) (C++17부터)

소스 범위 [first, last) 에서 주어진 조건을 만족하는 첫 번째 인접 요소 쌍을 검색합니다.

1) 인접한 동일한 요소의 첫 번째 쌍을 검색합니다. 동등성은 operator==을(를) 사용하여 결정됩니다.
2) 주어진 이진 술어 p을(를) 만족하는 첫 번째 인접 요소 쌍을 검색합니다.
3,4) (1,2)와 동일하지만 policy에 따라 실행됩니다.
이러한 오버로드는 다음 표현식의 값이 true인 경우에만 오버로드 해결에 참여합니다:

std::is_execution_policy_v<std::decay_t<ExecutionPolicy>>

(C++20까지)

std::is_execution_policy_v<std::remove_cvref_t<ExecutionPolicy>>

(C++20부터)

매개변수

first, last - 소스를 정의하는 반복자 쌍 범위
p - 이진 술어로, 다음을 반환합니다: true 요소를 같음으로 처리해야 하는 경우

술어 함수의 시그니처는 다음과 동등해야 합니다:

bool pred(const Type1 &a, const Type2 &b);

시그니처에 다음이 있을 필요는 없지만, const &, 함수는 전달된 객체를 수정하지 않아야 하며, (const일 수 있는) 타입의 모든 값을 받을 수 있어야 합니다: Type1 및 Type2와 관계없이 값 범주 (따라서 Type1 &는 허용되지 않습니다, Type1도 허용되지 않습니다. 단, Type1 이동이 복사와 동등한 경우는 예외(C++11부터)).
타입 Type1 및 Type2은(는) 다음을 만족해야 합니다: ForwardIt 타입의 객체가 역참조될 수 있고, 두 타입 모두로 암시적으로 변환될 수 있어야 합니다. ​

정책 - 사용할 실행 정책
타입 요구사항
-
ForwardIt는 다음의 요구사항을 충족해야 합니다: LegacyForwardIterator.
-
BinaryPred는 다음의 요구사항을 충족해야 합니다: BinaryPredicate.

반환값

첫 번째 반복자 iter는 소스 범위 내에서 다음 표현식이 true로 평가되는:

1,3) bool(*iter == *std::next(iter))
2,4) bool(p(*iter, std::next(iter))

그러한 반복자를 찾을 수 없는 경우 last이(가) 반환됩니다.

복잡도

주어진 result를(을) adjacent_find의 반환값으로 하고, M를(을) std::distance(first, result)로, N를(을) std::distance(first, last)로 할 때:

1) 정확히 min(M+1,N-1) 번의 비교 (operator== 사용).
2) 정확히 min(M+1,N-1) 번의 술어 p 적용.
3) 𝓞(N) 번의 비교 (operator== 사용).
4) 𝓞(N) 번의 술어 p 적용.

예외

3,4) 실행 과정 중:
  • 병렬화에 필요한 임시 메모리 자원을 사용할 수 없는 경우, std::bad_alloc가 발생합니다.
  • 알고리즘 인수를 통해 객체에 접근하는 동안 처리되지 않은 예외가 발생하면, 동작은 실행 정책에 따라 결정됩니다 (표준 정책, std::terminate이 호출됩니다).

가능한 구현

adjacent_find (1)
template<class ForwardIt>
ForwardIt adjacent_find(ForwardIt first, ForwardIt last)
{
    if (first == last)
        return last;
    
    ForwardIt next = first;
    ++next;
    
    for (; next != last; ++next, ++first)
        if (*first == *next)
            return first;
    
    return last;
}
adjacent_find (2)
template<class ForwardIt, class BinaryPred>
ForwardIt adjacent_find(ForwardIt first, ForwardIt last, BinaryPred p)
{
    if (first == last)
        return last;
    
    ForwardIt next = first;
    ++next;
    
    for (; next != last; ++next, ++first)
        if (p(*first, *next))
            return first;
    
    return last;
}

예제

#include <algorithm>
#include <functional>
#include <iostream>
#include <vector>
int main()
{
    std::vector<int> v1{0, 1, 2, 3, 40, 40, 41, 41, 5};
    auto i1 = std::adjacent_find(v1.begin(), v1.end());
    if (i1 == v1.end())
        std::cout << "No matching adjacent elements\n";
    else
        std::cout << "The first adjacent pair of equal elements is at "
                  << std::distance(v1.begin(), i1) << ", *i1 = "
                  << *i1 << '\n';
    auto i2 = std::adjacent_find(v1.begin(), v1.end(), std::greater<int>());
    if (i2 == v1.end())
        std::cout << "The entire vector is sorted in ascending order\n";
    else
        std::cout << "The last element in the non-decreasing subsequence is at "
                  << std::distance(v1.begin(), i2) << ", *i2 = " << *i2 << '\n';
}

출력:

The first adjacent pair of equal elements is at 4, *i1 = 40
The last element in the non-decreasing subsequence is at 7, *i2 = 41

결함 보고서

다음 동작 변경 결함 보고서는 이전에 발표된 C++ 표준에 소급 적용되었습니다.

DR 적용 대상 게시된 동작 올바른 동작
LWG 240 C++98 복잡성 요구 사항이 불명확했습니다 명확하게 함

참고 항목

처음으로 같거나 주어진 조건을 만족하는 인접한 두 항목을 찾습니다
(알고리즘 함수 객체)
범위에서 연속된 중복 요소를 제거합니다
(함수 템플릿 & 알고리즘 함수 객체)