當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


C++ Algorithm equal()用法及代碼示例


描述

C++ 函數std::algorithm::equal()測試兩組元素是否相等。兩個集合的大小不必相等。它用二元謂詞用於比較。

聲明

以下是 std::algorithm::equal() 函數形式 std::algorithm 頭文件的聲明。

C++98

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

參數

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

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

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

  • pred- 一個二元謂詞,它接受兩個參數並返回一個布爾值。

返回值

如果範圍內的所有元素都返回真第一個最後1等於開始於的範圍的那些第2個否則返回false。

異常

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

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

時間複雜度

之間的距離呈線性第一的最後的

示例

下麵的例子展示了 std::algorithm::equal() 函數的用法。

#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.

相關用法


注:本文由純淨天空篩選整理自 C++ Algorithm Library - equal() Function。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。