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
(注:指定されたテーブル行には翻訳対象のテキストが含まれていないため、HTML構造はそのまま維持されています)
定義済みヘッダー <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 として使用する場合と同様です。

このページで説明されている関数ライクな実体は、 アルゴリズム関数オブジェクト (非公式には niebloids として知られる)です。すなわち:

目次

パラメータ

first, last - 検査対象の要素の範囲を定義するイテレータ-センチネルペア( レンジ 、別名 干し草の山
r - 検査対象の要素の範囲(別名 干し草の山
count - 検索対象シーケンスの長さ
value - 検索する値(別名
pred - 射影された要素と value を比較する二項述語
proj - 検査対象レンジの要素に適用する射影

戻り値

1) 範囲 [ first , last ) 内で見つかった部分シーケンスを指定するイテレータのペアを含む std :: ranges:: subrange オブジェクトを返します。

そのような部分シーケンスが見つからない場合、 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; // valueと等しくない
                }
            }
        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);
}

出力:

ABBCDABBBA 内で部分シーケンス BBB を検索
位置 6 で発見

関連項目

等しい(または指定された述語を満たす)最初の隣接する2つの要素を検索する
(アルゴリズム関数オブジェクト)
特定の基準を満たす最初の要素を検索する
(アルゴリズム関数オブジェクト)
特定の範囲内で要素の最後のシーケンスを検索する
(アルゴリズム関数オブジェクト)
要素のセットのいずれかを検索する
(アルゴリズム関数オブジェクト)
あるシーケンスが別のシーケンスの部分シーケンスである場合に true を返す
(アルゴリズム関数オブジェクト)
2つの範囲が異なる最初の位置を検索する
(アルゴリズム関数オブジェクト)
要素の範囲の最初の出現を検索する
(アルゴリズム関数オブジェクト)
範囲内の要素の連続するコピーの最初の出現を検索する
(関数テンプレート)