Namespaces
Variants

std::ranges:: adjacent_find

From cppreference.net
Algorithm library
Constrained algorithms and algorithms on ranges (C++20)
Constrained algorithms, e.g. ranges::copy , ranges::sort , ...
Execution policies (C++17)
Non-modifying sequence operations
Batch operations
(C++17)
Search operations
Modifying sequence operations
Copy operations
(C++11)
(C++11)
Swap operations
Transformation operations
Generation operations
Removing operations
Order-changing operations
(until C++17) (C++11)
(C++20) (C++20)
Sampling operations
(C++17)

Sorting and related operations
Partitioning operations
Sorting operations
Binary search operations
(on partitioned ranges)
Set operations (on sorted ranges)
Merge operations (on sorted ranges)
Heap operations
Minimum/maximum operations
Lexicographical comparison operations
Permutation operations
C library
Numeric operations
Operations on uninitialized memory
Constrained algorithms
All names in this menu belong to namespace std::ranges
Non-modifying sequence operations
Modifying sequence operations
Partitioning operations
Sorting operations
Binary search operations (on sorted ranges)
Set operations (on sorted ranges)
Heap operations
Minimum/maximum operations
Permutation operations
Fold operations
Operations on uninitialized storage
Return types
헤더 파일에 정의됨 <algorithm>
함수 시그니처
template < std:: forward_iterator I, std:: sentinel_for < I > S, class Proj = std:: identity ,

std:: indirect_binary_predicate <
std :: projected < I, Proj > ,
std :: projected < I, Proj >> Pred = ranges:: equal_to >
constexpr I

adjacent_find ( I first, S last, Pred pred = { } , Proj proj = { } ) ;
(1) (C++20 이후)
template < ranges:: forward_range R, class Proj = std:: identity ,

std:: indirect_binary_predicate <
std :: projected < ranges:: iterator_t < R > , Proj > ,
std :: projected < ranges:: iterator_t < R > , Proj >> Pred = ranges:: equal_to >
constexpr ranges:: borrowed_iterator_t < R >

adjacent_find ( R && r, Pred pred = { } , Proj proj = { } ) ;
(2) (C++20 이후)

범위 [ first , last ) 내에서 처음으로 연속된 두 개의 동일한 요소를 검색합니다.

1) 요소들은 pred 를 사용하여 비교됩니다 (투영 함수 proj 로 투영한 후).
2) (1) 과 동일하지만, r 을 소스 범위로 사용하며, 마치 ranges:: begin ( r ) first 로, ranges:: end ( r ) last 로 사용하는 것과 같습니다.

이 페이지에서 설명하는 함수형 개체들은 algorithm function objects (일반적으로 niebloids 로 알려진)입니다. 즉:

목차

매개변수

first, last - 검사할 요소들의 범위 를 정의하는 반복자-감시자 쌍
r - 검사할 요소들의 범위
pred - 투영된 요소들에 적용할 조건자
proj - 요소들에 적용할 투영

반환값

첫 번째로 동일한 요소 쌍 중 첫 번째 요소에 대한 반복자, 즉 it bool ( std:: invoke ( pred, std:: invoke ( proj1, * it ) , std:: invoke ( proj, * ( it + 1 ) ) ) ) true 인 첫 번째 반복자를 가리킵니다.

해당하는 요소가 없으면, last 와 동일한 반복자가 반환됩니다.

복잡도

정확히 min ( ( result - first ) + 1 , ( last - first ) - 1 ) 번의 predicate와 projection 적용이 이루어지며, 여기서 result 는 반환 값입니다.

가능한 구현

struct adjacent_find_fn
{
    template<std::forward_iterator I, std::sentinel_for<I> S, class Proj = std::identity,
             std::indirect_binary_predicate<
                 std::projected<I, Proj>,
                 std::projected<I, Proj>> Pred = ranges::equal_to>
    constexpr I operator()(I first, S last, Pred pred = {}, Proj proj = {}) const
    {
        if (first == last)
            return first;
        auto next = ranges::next(first);
        for (; next != last; ++next, ++first)
            if (std::invoke(pred, std::invoke(proj, *first), std::invoke(proj, *next)))
                return first;
        return next;
    }
    template<ranges::forward_range R, class Proj = std::identity,
             std::indirect_binary_predicate<
                 std::projected<ranges::iterator_t<R>, Proj>,
                 std::projected<ranges::iterator_t<R>, Proj>> Pred = ranges::equal_to>
    constexpr ranges::borrowed_iterator_t<R>
        operator()(R&& r, Pred pred = {}, Proj proj = {}) const
    {
        return (*this)(ranges::begin(r), ranges::end(r), std::ref(pred), std::ref(proj));
    }
};
inline constexpr adjacent_find_fn adjacent_find;

예제

#include <algorithm>
#include <functional>
#include <iostream>
#include <ranges>
constexpr bool some_of(auto&& r, auto&& pred) // 일부만 해당(전체는 아님)
{
    return std::ranges::cend(r) != std::ranges::adjacent_find(r,
        [&pred](auto const& x, auto const& y)
        {
            return pred(x) != pred(y);
        });
}
// some_of 테스트
constexpr auto a = {0, 0, 0, 0}, b = {1, 1, 1, 0}, c = {1, 1, 1, 1};
auto is_one = [](auto x){ return x == 1; };
static_assert(!some_of(a, is_one) && some_of(b, is_one) && !some_of(c, is_one));
int main()
{
    const auto v = {0, 1, 2, 3, 40, 40, 41, 41, 5}; /*
                                ^^          ^^       */
    namespace ranges = std::ranges;
    if (auto it = ranges::adjacent_find(v.begin(), v.end()); it == v.end())
        std::cout << "인접한 동일 요소 쌍이 없습니다\n";
    else
        std::cout << "첫 번째 인접한 동일 요소 쌍의 위치 ["
                  << ranges::distance(v.begin(), it) << "] == " << *it << '\n';
    if (auto it = ranges::adjacent_find(v, ranges::greater()); it == v.end())
        std::cout << "전체 벡터가 오름차순으로 정렬되었습니다\n";
    else
        std::cout << "비감소 부분 수열의 마지막 요소 위치 ["
                  << ranges::distance(v.begin(), it) << "] == " << *it << '\n';
}

출력:

첫 번째 인접한 동일 요소 쌍의 위치 [4] == 40
비감소 부분 수열의 마지막 요소 위치 [7] == 41

참고 항목

범위에서 연속된 중복 요소를 제거함
(알고리즘 함수 객체)
서로 같은(또는 주어진 조건자를 만족하는) 첫 두 개의 인접 항목을 찾음
(함수 템플릿)