std::
equal
函数模板 <algorithm>
equality (1) |
template <class InputIterator1, class InputIterator2>
bool equal (InputIterator1 first1, InputIterator1 last1,
InputIterator2 first2); |
predicate(2) |
template <class InputIterator1, class InputIterator2, class BinaryPredicate>
bool equal (InputIterator1 first1, InputIterator1 last1,
InputIterator2 first2, BinaryPredicate pred); |
测试两个范围内的元素是否相等
将[first1,last1)范围内的元素与从first2开始的范围内的元素进行比较,
如果两个范围内的所有元素都匹配,则返回true。
使用operator==(或版本(2)中的pred)比较元素。
这个函数模板的行为相当于:
template <class InputIterator1, class InputIterator2>
bool equal ( InputIterator1 first1, InputIterator1 last1, InputIterator2 first2 )
{
while (first1!=last1) {
if (!(*first1 == *first2)) // or: if (!pred(*first1,*first2)), for version 2
return false;
++first1; ++first2;
}
return true;
} |
☲ 参数
-
first1, last1
-
指向第一个序列初始和最终位置的输入迭代器。使用的范围是[first1,last1],
它包含first1和last1之间的所有元素,包括first1指向的元素,但不包括last1指向的元素。
-
first2
-
指向第二个序列的初始位置的输入迭代器。函数最多可以访问[first1,last1]范围内的元素。
-
pred
-
接受两个元素(每个序列一个元素,顺序相同)作为参数并返回可转换为bool的值的二元函数。
返回值指示元素在此函数当前环境中是否被认为匹配。
函数不能修改它的任何参数。
它可以是函数指针,也可以是函数对象。
☉ 返回值
如果[first1,last1]范围内的所有元素的比较值都等于从first2开始的范围的比较值,
则为True,否则为false。
☣ 示例
// equal algorithm example
#include <iostream> // std::cout
#include <algorithm> // std::equal
#include <vector> // std::vector
bool mypredicate (int i, int j) {
return (i==j);
}
int main () {
int myints[] = {20,40,60,80,100}; // myints: 20 40 60 80 100
std::vector<int>myvector (myints,myints+5); // myvector: 20 40 60 80 100
// using default comparison:
if ( std::equal (myvector.begin(), myvector.end(), myints) )
std::cout << "The contents of both sequences are equal.\n";
else
std::cout << "The contents of both sequences differ.\n";
myvector[3]=81; // myvector: 20 40 60 81 100
// using predicate comparison:
if ( std::equal (myvector.begin(), myvector.end(), myints, mypredicate) )
std::cout << "The contents of both sequences are equal.\n";
else
std::cout << "The contents of both sequences differ.\n";
return 0;
} |
输出:
The contents of both sequences are equal.
The contents of both sequence differ.
✥ 复杂度
在first1 和last1之间的distance达到线性:比较元素,直到找到不匹配。
⇄ 数据竞争
两个范围内的部分(或全部)对象被访问(最多一次)。
☂ 异常安全性
如果任何元素比较(或pred)或迭代器上的任何操作抛出,则抛出。
注意,无效的参数会导致未定义的行为。
🍄 另请参阅
find_first_of |
从设置的范围查找元素(函数模板) |
find_end |
求范围内的最后一个子序列(函数模板) |
search |
搜索子序列的范围(函数模板) |
mismatch |
返回两个范围不匹配元素的第一个位置(函数模板) |