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 ) первой последовательности из 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) Списковая инициализация для алгоритмов

Возможная реализация

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) << " в ";
    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);
}

Вывод:

Найти подпоследовательность BBB в строке ABBCDABBBA
Найдено на позиции 6

Смотрите также

находит первые два соседних элемента, которые равны (или удовлетворяют заданному предикату)
(функциональный объект алгоритма)
находит первый элемент, удовлетворяющий определённым критериям
(функциональный объект алгоритма)
находит последнюю последовательность элементов в определённом диапазоне
(функциональный объект алгоритма)
ищет любой из набора элементов
(функциональный объект алгоритма)
возвращает true если одна последовательность является подпоследовательностью другой
(функциональный объект алгоритма)
находит первую позицию, в которой два диапазона различаются
(функциональный объект алгоритма)
ищет первое вхождение диапазона элементов
(функциональный объект алгоритма)
ищет первое вхождение заданного количества последовательных копий элемента в диапазоне
(шаблон функции)