algorithm_search_n

algorithm_search_n (연속 요소 탐색)

std::search_n는 소스 범위에서 value와 같은 count개의 연속된 요소가 처음 나타나는 위치를 찾아요.

출처: cppreference

본문

std::search_n는 소스 범위 [first, last)에서 value와 같은 count개의 연속 요소가 처음 나타나는 곳을 찾아요. <algorithm> 헤더에 정의되어 있어요.

template< class ForwardIt, class Size, class T >
ForwardIt search_n( ForwardIt first, ForwardIt last,
                    Size count, const T& value );

template< class ForwardIt, class Size, class T, class BinaryPred >
ForwardIt search_n( ForwardIt first, ForwardIt last,
                    Size count, const T& value, BinaryPred p );
  • 1번 오버로드 — 요소를 operator==로 비교해요.
  • 2번 오버로드 — 요소를 이진 술어 p로 비교해요.
  • 병렬 실행 정책을 받는 오버로드도 있어요.

반환값 (Return value)

count개의 연속 요소가 처음으로 나타나는 곳의 시작 반복자예요. 그런 시퀀스가 없으면 last를 돌려줘요. count가 0이면 first를 돌려줘요.

복잡도 (Complexity)

Nstd::distance(first, last)라고 하면 최대 N번의 비교가 필요해요.

예제 (Example)

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

int main()
{
    std::vector<int> v{1, 2, 3, 4, 4, 4, 5};
    auto it = std::search_n(v.begin(), v.end(), 3, 4);
    if (it != v.end())
        std::cout << "Found at index " << std::distance(v.begin(), it) << '\n';
}

출력:

Found at index 3

더 알아보기 (Learn more)

cppreference