命名空间
变体
操作

std::search_n

来自 cppreference.cn
< cpp‎ | 算法
 
 
算法库
有约束算法与针对范围的算法 (C++20)
有约束的算法,例如 ranges::copyranges::sort 等……
执行策略 (C++17)
排序及相关操作
划分操作
排序操作
二分搜索操作
(于已划分范围上)
集合操作(于已排序范围上)
归并操作(于已排序范围上)
堆操作
最小/最大值操作
(C++11)
(C++17)
字典序比较操作
排列操作
C 库
数值操作
未初始化内存上的操作
 
定义于头文件 <algorithm>
(1)
template< class ForwardIt, class Size, class T >

ForwardIt search_n( ForwardIt first, ForwardIt last,

                    Size count, const T& value );
(C++20 起为 constexpr)
(直到 C++26)
template< class ForwardIt, class Size,

          class T = typename std::iterator_traits
                        <ForwardIt>::value_type >
constexpr ForwardIt search_n( ForwardIt first, ForwardIt last,

                              Size count, const T& value );
(C++26 起)
(2)
template< class ExecutionPolicy,

          class ForwardIt, class Size, class T >
ForwardIt search_n( ExecutionPolicy&& policy,
                    ForwardIt first, ForwardIt last,

                    Size count, const T& value );
(C++17 起)
(直到 C++26)
template< class ExecutionPolicy,

          class ForwardIt, class Size,
          class T = typename std::iterator_traits
                        <ForwardIt>::value_type >
ForwardIt search_n( ExecutionPolicy&& policy,
                    ForwardIt first, ForwardIt last,

                    Size count, const T& value );
(C++26 起)
(3)
template< class ForwardIt, class Size, class T, class BinaryPred >

ForwardIt search_n( ForwardIt first, ForwardIt last,

                    Size count, const T& value, BinaryPred p );
(C++20 起为 constexpr)
(直到 C++26)
template< class ForwardIt, class Size,

          class T = typename std::iterator_traits
                        <ForwardIt>::value_type,
          class BinaryPred >
constexpr ForwardIt search_n( ForwardIt first, ForwardIt last,

                    Size count, const T& value, BinaryPred p );
(C++26 起)
(4)
template< class ExecutionPolicy, class ForwardIt, class Size,

          class T, class BinaryPred >
ForwardIt search_n( ExecutionPolicy&& policy,
                    ForwardIt first, ForwardIt last,

                    Size count, const T& value, BinaryPred p );
(C++17 起)
(直到 C++26)
template< class ExecutionPolicy, class ForwardIt, class Size,

          class T = typename std::iterator_traits
                        <ForwardIt>::value_type,
          class BinaryPred >
ForwardIt search_n( ExecutionPolicy&& policy,
                    ForwardIt first, ForwardIt last,

                    Size count, const T& value, BinaryPred p );
(C++26 起)

在范围 [firstlast) 中搜索第一个由 count 个相同元素组成的序列,每个元素都等于给定 value

1) 使用 operator== 比较元素。
3) 使用给定二元谓词 p 比较元素。
2,4)(1,3),但按 policy 执行。
仅当满足所有以下条件时,这些重载才参与重载决议

std::is_execution_policy_v<std::decay_t<ExecutionPolicy>>true

(C++20 前)

std::is_execution_policy_v<std::remove_cvref_t<ExecutionPolicy>>true

(C++20 起)

目录

[edit] 参数

first, last - 定义要检查的元素范围的迭代器对
count - 要搜索的序列长度
value - 要搜索的元素值
policy - 要使用的 执行策略
p - 二元谓词,如果元素应被视为相等,则返回 true。

谓词函数的签名应等效于以下内容:

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

尽管签名不需要包含 const &,但函数不得修改传递给它的对象,并且必须能够接受 Type1Type2 类型的所有值(可能为 const),而不管 值类别(因此,不允许 Type1 &,除非对于 Type1 移动等同于复制,否则也不允许 Type1(自 C++11 起))。
类型 Type1 必须使得类型为 ForwardIt 的对象可以被解引用,然后隐式转换为 Type1。类型 Type2 必须使得类型为 T 的对象可以隐式转换为 Type2。​

类型要求
-
ForwardIt 必须满足 LegacyForwardIterator 的要求。
-
BinaryPred 必须满足 BinaryPredicate 的要求。
-
Size 必须可隐式转换为整数类型

[edit] 返回值

如果 count 为正,则返回指向在范围 [firstlast) 中找到的第一个序列开头的迭代器。序列中的每个迭代器 it 都应满足以下条件

1,2) *it == valuetrue
3,4) p(*it, value) != falsetrue

如果未找到此类序列,则返回 last

如果 count 为零或负,则返回 first

[edit] 复杂度

给定 N 作为 std::distance(first, last)

1,2) 最多 N 次使用 operator== 的比较。
3,4) 最多 N 次谓词 p 的应用。

[edit] 异常

带有模板参数 ExecutionPolicy 的重载按如下方式报告错误

  • 如果作为算法一部分调用的函数执行抛出异常,并且 ExecutionPolicy标准策略之一,则调用 std::terminate。对于任何其他 ExecutionPolicy,行为是实现定义的。
  • 如果算法未能分配内存,则抛出 std::bad_alloc

[edit] 可能的实现

search_n (1)
template<class ForwardIt, class Size,
         class T = typename std::iterator_traits<ForwardIt>::value_type>
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;
 
        for (Size cur_count = 1; true; ++cur_count)
        {
            if (cur_count >= count)
                return candidate; // success
 
            ++first;
            if (first == last)
                return last; // exhausted the list
 
            if (!(*first == value))
                break; // too few in a row
        }
    }
    return last;
}
search_n (3)
template<class ForwardIt, class Size,
         class T = typename std::iterator_traits<ForwardIt>::value_type,
         class BinaryPred>
ForwardIt search_n(ForwardIt first, ForwardIt last, Size count, const T& value,
                   BinaryPred p)
{
    if (count <= 0)
        return first;
 
    for (; first != last; ++first)
    {
        if (!p(*first, value))
            continue;
 
        ForwardIt candidate = first;
 
        for (Size cur_count = 1; true; ++cur_count)
        {
            if (cur_count >= count)
                return candidate; // success
 
            ++first;
            if (first == last)
                return last; // exhausted the list
 
            if (!p(*first, value))
                break; // too few in a row
        }
    }
    return last;
}

[edit] 注意

特性测试 标准 特性
__cpp_lib_algorithm_default_value_type 202403 (C++26) 算法的列表初始化 (1-4)

[edit] 示例

#include <algorithm>
#include <cassert>
#include <complex>
#include <iostream>
#include <iterator>
#include <vector>
 
template<class Container, class Size, class T>
constexpr 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()
{
    constexpr char sequence[] = ".0_0.000.0_0.";
 
    static_assert(consecutive_values(sequence, 3, '0'));
 
    for (int n : {4, 3, 2})
        std::cout << std::boolalpha
                  << "Has " << n << " consecutive zeros: "
                  << consecutive_values(sequence, n, '0') << '\n';
 
    std::vector<std::complex<double>> nums{{4, 2}, {4, 2}, {1, 3}};
    #ifdef __cpp_lib_algorithm_default_value_type
        auto it = std::search_n(nums.cbegin(), nums.cend(), 2, {4, 2});
    #else
        auto it = std::search_n(nums.cbegin(), nums.cend(), 2, std::complex<double>{4, 2});
    #endif
    assert(it == nums.begin());
}

输出

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

[edit] 缺陷报告

下列更改行为的缺陷报告追溯地应用于以前出版的 C++ 标准。

缺陷报告 应用于 发布时的行为 正确的行为
LWG 283 C++98 要求 TEqualityComparable,但
InputIt 的值类型并非总是 T
移除了此要求
LWG 426 C++98 复杂度上限为 N·count
如果 count 为负,则为负
上限为 0
如果 count 为非正
LWG 714 C++98 如果 count > 0,复杂度上限为 N·count,但在
最坏情况下,比较/操作次数始终为 N
在这种情况下将上限
更改为 N
LWG 2150 C++98 “序列出现”的条件不正确 已更正

[edit] 另请参阅

在特定范围中寻找最后一次出现的元素序列
(函数模板) [编辑]
寻找第一个满足特定条件的元素
(函数模板) [编辑]
搜索一个范围的元素首次出现的位置
(函数模板) [编辑]
在一个范围内搜索一个元素的连续 N 次副本首次出现的位置
(算法函数对象)[编辑]