函式模板
<algorithm>

std::equal

相等 (1)
template <class InputIterator1, class InputIterator2>  bool equal (InputIterator1 first1, InputIterator1 last1,              InputIterator2 first2);
謂詞 (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)進行比較。

此函式模板的行為等同於
1
2
3
4
5
6
7
8
9
10
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),它包含 first1last1 之間的所有元素,包括 first1 指向的元素,但不包括 last1 指向的元素。
first2
輸入迭代器 指向第二個序列的初始位置。比較將包含該序列中與範圍 [first1,last1) 中元素數量相同的元素。
pred
二元函式,接受兩個元素作為引數(分別來自兩個序列,順序相同),並返回一個可轉換為 bool 的值。返回的值表示在當前函式上下文中,元素是否被視為匹配。
該函式不得修改其任何引數。
這可以是指向函式的指標,也可以是函式物件。

返回值

如果範圍 [first1,last1) 中的所有元素都與以 first2 開頭的範圍中的元素相等,則返回 true,否則返回 false

示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
// 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.


複雜度

線性時間,最多與 first1last1 之間的 距離 相關:比較元素直到找到不匹配項。

資料競爭

兩個範圍中的一些(或全部)物件將被訪問(最多一次)。

異常

如果任何元素比較(或 pred)丟擲異常,或者任何迭代器操作丟擲異常,則丟擲異常。
請注意,無效的引數會導致 *未定義行為*。

另見