Namespaces
Variants

std::ranges::search_n

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

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


 
제약 알고리즘
이 메뉴의 모든 이름은 네임스페이스 std::ranges
비수정 시퀀스 연산
수정 시퀀스 연산
분할 연산
정렬 연산
이진 탐색 연산 (정렬된 범위에서)
       
       
집합 연산 (정렬된 범위에서)
힙 연산
최소/최대 연산
       
       
순열 연산
폴드 연산
수치 연산
(C++23)            
초기화되지 않은 저장소에 대한 연산
반환 타입
 
헤더에 정의됨 <algorithm>
호출 시그니처
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 = {} );
(1) (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부터)
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 = {} );
(2) (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) 범위에서 첫 번째 시퀀스의 count 개의 요소 (투영된 값이 각각 주어진 value와 같으며)를 이진 조건자 pred에 따라 검색합니다.
2) (1)과 동일하지만, 대신 r를 소스 범위로 사용하며, 마치 ranges::begin(r)를 first와 ranges::end(r)를 last로 사용하는 것처럼.

이 페이지에 설명된 함수형 엔터티는 알고리즘 함수 객체 (비공식적으로 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에서 발견됨

같이 보기

처음으로 나오는 인접한 두 항목이 같거나 (주어진 조건을 만족하는) 항목을 찾습니다
(알고리즘 함수 객체)
특정 조건을 만족하는 첫 번째 요소를 찾습니다
(알고리즘 함수 객체)
특정 범위에서 마지막으로 나타나는 요소 시퀀스를 찾습니다
(알고리즘 함수 객체)
요소 집합 중 하나를 검색합니다
(알고리즘 함수 객체)
하나의 시퀀스가 다른 시퀀스의 부분 시퀀스인지 판단합니다
(알고리즘 함수 객체)
두 범위가 달라지는 첫 번째 위치를 찾습니다
(알고리즘 함수 객체)
요소 범위가 처음 나타나는 위치를 검색합니다
(알고리즘 함수 객체)
범위 내에서 특정 개수의 연속된 요소 복사본이 처음 나타나는 위치를 검색합니다
(함수 템플릿)