STL find_first_of函数

STL find_first_of函数算法

STL 中,find_first_of() 函数用于在 A 序列中查找和 B 序列中任意元素相匹配的第一个元素。

STL find_first_of函数详解

头文件

#include <algorithm>

语法

//以判断两者相等作为匹配规则 InputIterator find_first_of (InputIterator first1, InputIterator last1, ForwardIterator first2, ForwardIterator last2); //以 pred 作为匹配规则 InputIterator find_first_of (InputIterator first1, InputIterator last1, ForwardIterator first2, ForwardIterator last2, BinaryPredicate pred);

参数

参数 描述
first1 输入迭代器
last1 输入迭代器
first2 正向迭代器
last2 正向迭代器
pred 可接收一个包含 2 个形参且返回值类型为 bool 的函数,该函数可以是普通函数(又称为二元谓词函数),也可以是函数对象。

说明

first1、last1:都为输入迭代器,它们的组合 [first1, last1) 用于指定该函数要查找的范围;first2、last2:都为正向迭代器,它们的组合 [first2, last2) 用于指定要进行匹配的元素所在的范围;

pred:可接收一个包含 2 个形参且返回值类型为 bool 的函数,该函数可以是普通函数(又称为二元谓词函数),也可以是函数对象。

技术细节

find_first_of() 函数用于在 [first1, last1) 范围内查找和 [first2, last2) 中任何元素相匹配的第一个元素。如果匹配成功,该函数会返回一个指向该元素的输入迭代器;反之,则返回一个和 last1 迭代器指向相同的输入迭代器。

值得一提的是,不同语法格式的匹配规则也是不同的:

  • 第 1 种语法格式:逐个取 [first1, last1) 范围内的元素(假设为 A),和 [first2, last2) 中的每个元素(假设为 B)做 A==B 运算,如果成立则匹配成功;
  • 第 2 种语法格式:逐个取 [first1, last1) 范围内的元素(假设为 A),和 [first2, last2) 中的每个元素(假设为 B)一起带入 pred(A, B) 谓词函数,如果函数返回 true 则匹配成功。

注意,当采用第一种语法格式时,如果 [first1, last1) 或者 [first2, last2) 范围内的元素类型为自定义的类对象或者结构体变量,此时应对 == 运算符进行重载,使其适用于当前场景。

案例

STL find_first_of函数

使用 STL find_first_of 函数查找集合

#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; char url[] = "https://www.haicoder.net"; char ch[] = "haicoder"; char *it = find_first_of(url, url + 24, ch, ch + 4); if (it != url + 24) { cout << "*it = " << *it << '\n'; } vector<int> myvector{102, 1024, 99, 110}; int inter[] = {100, 101, 99}; vector<int>::iterator iter = find_first_of(myvector.begin(), myvector.end(), inter, inter + 3, mycomp()); if (iter != myvector.end()) { cout << "*iter = " << *iter; } cout << endl; return 0; }

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

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

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

14_STL find_first_of函数.png

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

STL find_first_of函数总结

在 STL 中,find_first_of() 函数用于在 A 序列中查找和 B 序列中任意元素相匹配的第一个元素。