Namespaces
Variants

std::ranges:: search_n

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>
호출 시그니처
(1)
template < std:: forward_iterator I, std:: sentinel_for < I > S, class T,

class Pred = ranges:: equal_to , class Proj = std:: identity >
requires std:: indirectly_comparable < I, const T * , Pred, Proj >
constexpr ranges:: subrange < I >
search_n ( I first, S last, std:: iter_difference_t < I > count,

const T & value, Pred pred = { } , Proj proj = { } ) ;
(C++20부터)
(C++26까지)
template < std:: forward_iterator I, std:: sentinel_for < I > S,

class Pred = ranges:: equal_to , class Proj = std:: identity ,
class T = std :: projected_value_t < I, Proj > >
requires std:: indirectly_comparable < I, const T * , Pred, Proj >
constexpr ranges:: subrange < I >
search_n ( I first, S last, std:: iter_difference_t < I > count,

const T & value, Pred pred = { } , Proj proj = { } ) ;
(C++26부터)
(2)
template < ranges:: forward_range R, class T,

class Pred = ranges:: equal_to , class Proj = std:: identity >
requires std:: indirectly_comparable
< ranges:: iterator_t < R > , const T * , Pred, Proj >
constexpr ranges:: borrowed_subrange_t < R >
search_n ( R && r, ranges:: range_difference_t < R > count,

const T & value, Pred pred = { } , Proj proj = { } ) ;
(C++20부터)
(C++26까지)
template < ranges:: forward_range R,

class Pred = ranges:: equal_to , class Proj = std:: identity ,
class T = std :: projected_value_t < ranges:: iterator_t < R > , Proj > >
requires std:: indirectly_comparable
< ranges:: iterator_t < R > , const T * , Pred, Proj >
constexpr ranges:: borrowed_subrange_t < R >
search_n ( R && r, ranges:: range_difference_t < R > count,

const T & value, Pred pred = { } , Proj proj = { } ) ;
(C++26부터)
1) 범위 [ first , last ) 에서 이진 조건자 pred 에 따라 투영된 값이 각각 주어진 value 와 동일한 count 개의 요소로 이루어진 첫 번째 시퀀스를 검색합니다.
2) (1) 과 동일하지만, r 을 소스 범위로 사용하며, 마치 ranges:: begin ( r ) first 로, ranges:: end ( r ) last 로 사용하는 것과 같습니다.

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

  • 명시적 템플릿 인수 목록은 이들 중 어느 것을 호출할 때도 지정할 수 없습니다.
  • 이들 중 어느 것도 인수 의존 탐색 에 보이지 않습니다.
  • 이들 중 어느 것이 함수 호출 연산자의 왼쪽 이름으로 일반 비한정 탐색 에 의해 발견될 때, 인수 의존 탐색 이 억제됩니다.

목차

매개변수

first, last - 검사할 요소들의 범위 를 정의하는 반복자-감시자 쌍 (일명 haystack )
r - 검사할 요소들의 범위 (일명 haystack )
count - 검색할 시퀀스의 길이
value - 검색할 값 (일명 needle )
pred - 투영된 요소들을 value 와 비교하는 이항 조건자
proj - 검사할 범위의 요소들에 적용할 투영

반환값

1) std :: ranges:: subrange 객체를 반환하며, 이 객체는 찾은 부분 시퀀스를 지정하는 [ first , last ) 범위 내의 한 쌍의 반복자를 포함합니다.

해당 부분 시퀀스를 찾지 못한 경우, std :: ranges:: subrange { last, last } 을 반환합니다.

만약 count <= 0 이면, std :: ranges:: subrange { first, first } 을 반환합니다.
2) (1) 과 동일하지만 반환 타입은 ranges:: borrowed_subrange_t < R > 입니다.

복잡도

선형: 최대 ranges:: distance ( first, last ) 번의 술어와 투영 함수 적용.

참고 사항

구현은 반복자가 std:: random_access_iterator 를 모델링하는 경우 평균적으로 검색 효율을 향상시킬 수 있습니다.

기능 테스트 매크로 표준 기능
__cpp_lib_algorithm_default_value_type 202403 (C++26) 목록 초기화 for algorithms

가능한 구현

struct search_n_fn
{
    template<std::forward_iterator I, std::sentinel_for<I> S,
             class Pred = ranges::equal_to, class Proj = std::identity,
             class T = std::projected_value_t<I, Proj>>
    requires std::indirectly_comparable<I, const T*, Pred, Proj>
    constexpr ranges::subrange<I>
        operator()(I first, S last, std::iter_difference_t<I> count,
                   const T& value, Pred pred = {}, Proj proj = {}) const
    {
        if (count <= 0)
            return {first, first};
        for (; first != last; ++first)
            if (std::invoke(pred, std::invoke(proj, *first), value))
            {
                I start = first;
                std::iter_difference_t<I> n{1};
                for (;;)
                {
                    if (n++ == count)
                        return {start, std::next(first)}; // 발견됨
                    if (++first == last)
                        return {first, first}; // 발견되지 않음
                    if (!std::invoke(pred, std::invoke(proj, *first), value))
                        break; // 값과 같지 않음
                }
            }
        return {first, first};
    }
    template<ranges::forward_range R,
             class Pred = ranges::equal_to, class Proj = std::identity,
             class T = std::projected_value_t<ranges::iterator_t<R>, Proj>>
    requires std::indirectly_comparable<ranges::iterator_t<R>, const T*, Pred, Proj>
    constexpr ranges::borrowed_subrange_t<R>
        operator()(R&& r, ranges::range_difference_t<R> count,
                   const T& value, Pred pred = {}, Proj proj = {}) const
    {
        return (*this)(ranges::begin(r), ranges::end(r),
                       std::move(count), value,
                       std::move(pred), std::move(proj));
    }
};
inline constexpr search_n_fn search_n {};

예제

#include <algorithm>
#include <cassert>
#include <complex>
#include <iomanip>
#include <iostream>
#include <iterator>
#include <string>
#include <vector>
int main()
{
    namespace ranges = std::ranges;
    static constexpr auto nums = {1, 2, 2, 3, 4, 1, 2, 2, 2, 1};
    constexpr int count{3};
    constexpr int value{2};
    typedef int count_t, value_t;
    constexpr auto result1 = ranges::search_n
    (
        nums.begin(), nums.end(), count, value
    );
    static_assert // 찾음
    (
        result1.size() == count &&
        std::distance(nums.begin(), result1.begin()) == 6 &&
        std::distance(nums.begin(), result1.end()) == 9
    );
    constexpr auto result2 = ranges::search_n(nums, count, value);
    static_assert // 찾음
    (
        result2.size() == count &&
        std::distance(nums.begin(), result2.begin()) == 6 &&
        std::distance(nums.begin(), result2.end()) == 9
    );
    constexpr auto result3 = ranges::search_n(nums, count, value_t{5});
    static_assert // 찾을 수 없음
    (
        result3.size() == 0 &&
        result3.begin() == result3.end() &&
        result3.end() == nums.end()
    );
    constexpr auto result4 = ranges::search_n(nums, count_t{0}, value_t{1});
    static_assert // 찾을 수 없음
    (
        result4.size() == 0 &&
        result4.begin() == result4.end() &&
        result4.end() == nums.begin()
    );
    constexpr char symbol{'B'};
    auto to_ascii = [](const int z) -> char { return 'A' + z - 1; };
    auto is_equ = [](const char x, const char y) { return x == y; };
    std::cout << "부분 수열 찾기" << std::string(count, symbol) << " in the ";
    std::ranges::transform(nums, std::ostream_iterator<char>(std::cout, ""), to_ascii);
    std::cout << '\n';
    auto result5 = ranges::search_n(nums, count, symbol, is_equ, to_ascii);
    if (not result5.empty())
        std::cout << "위치에서 발견됨 "
                  << ranges::distance(nums.begin(), result5.begin()) << '\n';
    std::vector<std::complex<double>> nums2{{4, 2}, {4, 2}, {1, 3}};
    #ifdef __cpp_lib_algorithm_default_value_type
        auto it = ranges::search_n(nums2, 2, {4, 2});
    #else
        auto it = ranges::search_n(nums2, 2, std::complex<double>{4, 2});
    #endif
    assert(it.size() == 2);
}

출력:

ABBCDABBBA에서 부분 수열 BBB를 찾음
위치 6에서 발견됨

참고 항목

서로 인접한 두 항목 중 첫 번째로 동일한(또는 주어진 조건자를 만족하는) 항목을 찾음
(알고리즘 함수 객체)
특정 기준을 만족하는 첫 번째 요소를 찾음
(알고리즘 함수 객체)
특정 범위에서 마지막 요소 시퀀스를 찾음
(알고리즘 함수 객체)
요소 집합 중 하나를 검색함
(알고리즘 함수 객체)
하나의 시퀀스가 다른 시퀀스의 부분 시퀀스인 경우 true 를 반환함
(알고리즘 함수 객체)
두 범위가 처음으로 달라지는 위치를 찾음
(알고리즘 함수 객체)
요소 범위의 첫 번째 발생을 검색함
(알고리즘 함수 객체)
범위 내 요소의 연속된 복사본이 지정된 개수만큼 처음 나타나는 위치를 검색함
(함수 템플릿)