C++ 演算法庫 - equal() 函式



描述

C++ 函式std::algorithm::equal()測試兩組元素是否相等。兩組的大小不必相等。它使用二元謂詞進行比較。

宣告

以下是來自std::algorithm標頭檔案的std::algorithm::equal()函式的宣告。

C++98

template <class InputIterator1, class InputIterator2, class BinaryPredicate>
bool equal(InputIterator1 first1, InputIterator1 last1,
   InputIterator2 first2, BinaryPredicate pred);

引數

  • first1 - 第一個序列的初始位置的輸入迭代器。

  • last1 - 第一個序列的最終位置的輸入迭代器。

  • first2 - 第二個序列的初始位置的輸入迭代器。

  • pred - 一個接受兩個引數並返回bool值的二元謂詞。

返回值

如果從first1last1範圍內的所有元素都等於從first2開始的範圍內的元素,則返回true;否則返回false。

異常

如果元素比較(或謂詞)或迭代器上的操作丟擲異常,則丟擲異常。

請注意,無效引數會導致未定義的行為。

時間複雜度

線性於firstlast.

之間的距離

示例

#include <iostream>
#include <vector>
#include <algorithm>
#include <string>

using namespace std;

/* Binary predicate which always returns true */
bool binary_pred(string s1, string s2) {
   return true;
}

int main(void) {
   vector<string> v1 = {"one", "two", "three"};
   vector<string> v2 = {"ONE", "THREE", "THREE"};
   bool result;

   result = equal(v1.begin(), v1.end(), v2.begin(), binary_pred);

   if (result == true)
      cout << "Vector range is equal." << endl;

   return 0;
}

讓我們編譯並執行上面的程式,這將產生以下結果:

Vector range is equal.
algorithm.htm
廣告