STL equal函数

STL equal函数算法

STL 中的 equal 函数用于比较两个序列,如果两个序列的长度相同,并且对应元素都相等,equal() 算法会返回 true。

有 4 个版本的 equal() 算法,其中两个用 == 运算符来比较元素,另外两个用我们提供的作为参数的函数对象来比较元素,所有指定序列的迭代器都必须至少是输入迭代器。

用 == 运算符来比较两个序列的第一个版本期望 3 个输入迭代器参数,前两个参数是第一个序列的开始和结束迭代器,第三个参数是第二个序列的开始迭代器。如果第二个序列中包含的元素少于第一个序列,结果是未定义的。

用 == 运算符的第二个版本期望 4 个参数:第一个序列的开始和结束迭代器,第二个序列的开始和结束迭代器,如果两个序列的长度不同,那么结果总是为 false。

STL equal函数详解

头文件

#include <algorithm>

语法

template<class InputIterator1, class InputIterator2> bool equal( InputIterator1 _First1, InputIterator1 _Last1, InputIterator2 _First2 ); template<class InputIterator1, class InputIterator2, class BinaryPredicate> bool equal( InputIterator1 _First1, InputIterator1 _Last1, InputIterator2 _First2, BinaryPredicate _Comp );

参数

参数 描述
_First1 输入迭代器
_Last1 输入迭代器
_First2 输入迭代器
_Comp 自定义比较规则

案例

STL equal函数

使用 STL equal 函数比较集合

#include <iostream> #include <algorithm> #include <vector> int main() { std::cout << "嗨客网(www.haicoder.net)\n" << std::endl; std::vector<std::string> vc1{"one", "two", "three", "four", "five", "six", "seven", "eight", "nine"}; std::vector<std::string> vc2{"two", "three", "four", "five", "six", "seven", "eight", "nine", "ten"}; auto iter1 = std::begin(vc1); auto end_iter1 = std::end(vc1); auto iter2 = std::begin(vc2); if (std::equal(iter1, end_iter1, iter1)) { std::cout << "vc1 == vc1" << std::endl; } else { std::cout << "vc1 != vc1" << std::endl; } }

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

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

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

31_STL equal函数.png

我们使用了 equal 函数,判断了两个 vector 是否相等。

STL equal函数

使用 STL equal 函数比较集合

#include <iostream> #include <algorithm> #include <vector> int main() { std::cout << "嗨客网(www.haicoder.net)\n" << std::endl; std::vector<std::string> vc1{"one", "two", "three", "four", "five", "six", "seven", "eight", "nine"}; std::vector<std::string> vc2{"two", "three", "four", "five", "six", "seven", "eight", "nine", "ten"}; auto iter1 = std::begin(vc1); auto end_iter1 = std::end(vc1); auto iter2 = std::begin(vc2); if (std::equal(iter1, end_iter1, iter2)) { std::cout << "vc1 == vc2" << std::endl; } else { std::cout << "vc1 != vc2" << std::endl; } }

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

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

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

32_STL equal函数.png

我们使用了 equal 函数,判断了两个 vector 是否相等。

STL equal函数总结

STL 中的 equal 函数用于比较两个序列,如果两个序列的长度相同,并且对应元素都相等,equal() 算法会返回 true。

有 4 个版本的 equal() 算法,其中两个用 == 运算符来比较元素,另外两个用我们提供的作为参数的函数对象来比较元素,所有指定序列的迭代器都必须至少是输入迭代器。