# std::search_n

From cppreference.com
< cpp‎ | algorithm

Defined in header `<algorithm>` |  |
| (1) |
template< class ForwardIt, class Size, class T > ForwardIt search_n( ForwardIt first, ForwardIt last, Size count, const T& value ); |  | (until C++20)
template< class ForwardIt, class Size, class T > constexpr ForwardIt search_n( ForwardIt first, ForwardIt last, Size count, const T& value ); |  | (since C++20)
template< class ExecutionPolicy, class ForwardIt, class Size, class T > ForwardIt search_n( ExecutionPolicy&& policy, ForwardIt first, ForwardIt last, Size count, const T& value ); | (2) | (since C++17)
| (3) |
template< class ForwardIt, class Size, class T, class BinaryPredicate > ForwardIt search_n( ForwardIt first, ForwardIt last, Size count, const T& value, BinaryPredicate p ); |  | (until C++20)
template< class ForwardIt, class Size, class T, class BinaryPredicate > constexpr ForwardIt search_n( ForwardIt first, ForwardIt last, Size count, const T& value, BinaryPredicate p ); |  | (since C++20)
template< class ExecutionPolicy, class ForwardIt, class Size, class T, class BinaryPredicate > ForwardIt search_n( ExecutionPolicy&& policy, ForwardIt first, ForwardIt last, Size count, const T& value, BinaryPredicate p ); | (4) | (since C++17)

Searches the range `[first, last)` for the first sequence of count identical elements, each equal to the given value value.

1) Elements are compared using `operator==`.
3) Elements are compared using the given binary predicate `p`.
2,4) Same as (1,3), but executed according to `policy`. These overloads do not participate in overload resolution unless std::is_execution_policy_v < std::decay_t <ExecutionPolicy>> is true

### Parameters

first, last | - | the range of elements to examine
count | - | the length of the sequence to search for
value | - | the value of the elements to search for
policy | - | the execution policy to use. See execution policy for details.

p

-

binary predicate which returns ​true if the elements should be treated as equal.

The signature of the predicate function should be equivalent to the following:

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

While the signature does not need to have const &, the function must not modify the objects passed to it and must be able to accept all values of type (possibly const) `Type1` and `Type2` regardless of value category (thus, Type1 & is not allowed, nor is Type1 unless for `Type1` a move is equivalent to a copy (since C++11)).
The type Type1 must be such that an object of type ForwardIt can be dereferenced and then implicitly converted to Type1. The type Type2 must be such that an object of type T can be implicitly converted to Type2. ​

Type requirements
- `ForwardIt` must meet the requirements of LegacyForwardIterator.

### Return value

Iterator to the beginning of the found sequence in the range `[first, last)`. If no such sequence is found, `last` is returned.
If `count` is zero or negative, `first` is returned.

### Complexity

At most `last - first` applications of the predicate.

### Exceptions

The overloads with a template parameter named `ExecutionPolicy` report errors as follows:

- If execution of a function invoked as part of the algorithm throws an exception and `ExecutionPolicy` is one of the standard policies, std::terminate is called. For any other `ExecutionPolicy`, the behavior is implementation-defined.
- If the algorithm fails to allocate memory, std::bad_alloc is thrown.

### Possible implementation

First version

    template<class ForwardIt, class Size, class T>
    ForwardIt search_n(ForwardIt first, ForwardIt last,
                        Size count, const T& value)
    {
        if (count <= 0) {
            return first;
        }
        for(; first != last; ++first) {
            if (!(*first == value)) {
                continue;
            }

            ForwardIt candidate = first;
            Size cur_count = 0;

            while (true) {
                ++cur_count;
                if (cur_count >= count) {
                    // success
                    return candidate;
                }
                ++first;
                if (first == last) {
                    // exhausted the list
                    return last;
                }
                if (!(*first == value)) {
                    // too few in a row
                    break;
                }
            }
        }
        return last;
    }

Second version

    template<class ForwardIt, class Size, class T, class BinaryPredicate>
    ForwardIt search_n(ForwardIt first, ForwardIt last,
                        Size count, const T& value, BinaryPredicate p)
    {
        if (count <= 0) {
            return first;
        }
        for(; first != last; ++first) {
            if (!p(*first, value)) {
                continue;
            }

            ForwardIt candidate = first;
            Size cur_count = 0;

            while (true) {
                ++cur_count;
                if (cur_count >= count) {
                    // success
                    return candidate;
                }
                ++first;
                if (first == last) {
                    // exhausted the list
                    return last;
                }
                if (!p(*first, value)) {
                    // too few in a row
                    break;
                }
            }
        }
        return last;
    }

### Example

Run this code

    #include <iostream>
    #include <algorithm>
    #include <iterator>

    template <class Container, class Size, class T>
    bool consecutive_values(const Container& c, Size count, const T& v)
    {
      return std::search_n(std::begin(c),std::end(c),count,v) != std::end(c);
    }

    int main()
    {
       const char sequence[] = "1001010100010101001010101";

       std::cout << std::boolalpha;
       std::cout << "Has 4 consecutive zeros: "
                 << consecutive_values(sequence,4,'0') << '\n';
       std::cout << "Has 3 consecutive zeros: "
                 << consecutive_values(sequence,3,'0') << '\n';
    }

Output:

    Has 4 consecutive zeros: false
    Has 3 consecutive zeros: true

### See also

find_end | finds the last sequence of elements in a certain range (function template)
findfind_iffind_if_not (C++11) | finds the first element satisfying specific criteria (function template)
search | searches for a range of elements (function template)

Retrieved from "https://en.cppreference.com/mwiki/index.php?title=cpp/algorithm/search_n&oldid=108774"