C++ find_first_of()函数完全攻略

1年前 (2024-04-28)
在某些情境中,我们可能需要在 A 序列中查找和 B 序列中任意元素相匹配的个元素,这时就可以使用 find_first_of() 函数。

仅仅用一句话概述 find_first_of() 函数的功能,读者可能并不理解。别急,下面我们将从语法格式的角度继续阐述该函数的功能。

find_first_of() 函数定义于<algorithm>头文件中,因此使用该函数之前,程序中要先引入此头文件:

#include <algorithm>


find_first_of() 函数有 2 种语法格式,分别是:

//以判断两者相等作为匹配规则

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:都为输入迭代器,它们的组 [first1, last1) 用于指定该函数要查找的范围;

  • first2、last2:都为正向迭代器,它们的组 [first2, last2) 用于指定要进行匹配的元素所在的范围;

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

有关谓词函数,读者可阅读《C++谓词函数》一节详细了解。

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) 范围内的元素类型为自定义的类对象或者结构体变量,此时应对 == 运算符进行重载,使其适用于当前场景。

举个例子:

#include <iostream> // std::cout

#include <algorithm> // std::find_first_of

#include <vector> // std::vector

using namespace std;

//自定义二元谓词函数,作为 find_first_of() 函数的匹配规则

bool mycomp(int c1, int c2) {

return (c2 % c1 == 0);

}

//以函数对象的形式定义一个 find_first_of() 函数的匹配规则

class mycomp2 {

public:

bool operator()(const int& c1, const int& c2) {

return (c2 % c1 == 0);

}

};

int main() {

char url[] = "http://c.biancheng网站站点" rel="nofollow" /> *it = t

*iter = 3

此程序给读者演示了 find_first_of() 函数 2 种语法格式的用法。其中第 20 行代码中 find_first_of() 函数发挥的功能是,在 url 字符数组中逐个查找和 's'、't'、'l' 这 3 个字符相等的字符,显然 url 数组第 2 个字符 't' 就符此规则。

在第 29 行代码中,find_first_of() 会逐个提取 myvector 容器中的每个元素(假设为 A),并尝试和 inter 数组中的每个元素(假设为 B)一起带入 mycomp2(A, B) 函数对象中。显然,当将 myvector 容器中的元素 3 和 inter 数组中的元素 6 带入该函数时,c2 % c1=0 表达式次成立。

C++ STL 标准库给出了 find_first_of() 函数底层实现的参考代码,感兴趣的读者可自行分析:

template<class InputIt, class ForwardIt, class BinaryPredicate>

InputIt find_first_of(InputIt first, InputIt last,

ForwardIt s_first, ForwardIt s_last,

BinaryPredicate p)

{

for (; first != last; ++first) {

for (ForwardIt it = s_first; it != s_last; ++it) {

//第二种语法格式换成 if (p(*first, *it))

if (p(*first, *it)) {

return first;

}

}

}

return last;

}