STL search_n函数

STL search_n函数算法

STL 中 search_n() 函数用于在指定区域内查找第一个符合要求的子序列。与 search 函数不同之处在于,前者查找的子序列中可包含多个不同的元素,而后者查找的只能是包含多个相同元素的子序列。

STL search_n函数详解

头文件

#include <algorithm>

语法

//在 [first, last] 中查找 count 个 val 第一次连续出现的位置 ForwardIterator search_n (ForwardIterator first, ForwardIterator last, Size count, const T& val); //在 [first, last] 中查找第一个序列,该序列和 count 个 val 满足 pred 匹配规则 ForwardIterator search_n ( ForwardIterator first, ForwardIterator last, Size count, const T& val, BinaryPredicate pred );

参数

参数 描述
first 正向迭代器
last 正向迭代器
count 要查找的元素个数
val 要查找的元素值
pred 用于自定义查找规则。该规则实际上是一个包含 2 个参数且返回值类型为 bool 的函数。

说明

第一种语法格式也可以看做是包含一个默认的 pred 参数,该参数指定的是一种相等规则,即在 [first, last) 范围内查找和 count 个 val 相等的子序列;而借助第二种语法格式,我们可以自定义一个当前场景需要的匹配规则。

技术细节

search_n() 函数会返回一个正向迭代器,当函数查找成功时,该迭代器指向查找到的子序列中的第一个元素;反之,如果查找失败,则该迭代器的指向和 last 迭代器相同。

案例

STL search_n函数

使用 STL search_n 函数查找集合

#include <iostream> #include <algorithm> #include <vector> using namespace std; class mycomp { public: bool operator()(const int& i, const int& j) { return (i%j == 0); } }; int main() { cout << "嗨客网(www.haicoder.net)\n" << endl; int a[] = { 1,2,3,4,4,4,1,2,3,4,4,4 }; int * it = search_n(a, a+12, 3, 4); if (it != a+12) { cout << "Find: " << it - a << ", *it = " << *it << endl; } vector<int> myvector{1,2,4,8,3,4,6,8}; vector<int>::iterator iter = search_n(myvector.begin(), myvector.end(), 3, 2, mycomp()); if (iter != myvector.end()) { cout << "Find: " << iter - myvector.begin() << ", *iter = " << *iter; } cout << endl; return 0; }

我们在 Linux 下使用 g++ 进行编译,具体命令如下:

g++ search_n.cpp -std=c++11

编译后,我们直接运行生成的二进制文件 a.out,如下图所示:

17_STL search_n函数.png

我们使用了 search_n 函数,分别在数组和在 vector 中查找了元素。

STL search_n函数总结

在 STL 中 search_n() 函数用于在指定区域内查找第一个符合要求的子序列。与 search 函数不同之处在于,前者查找的子序列中可包含多个不同的元素,而后者查找的只能是包含多个相同元素的子序列。