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


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


std::equal()有助於將[first_1,last_1)範圍內的元素與從first_2開始的範圍內的元素進行比較。
語法1:

template 
  bool equal (InputIterator1 first1, InputIterator1 last1,
              InputIterator2 first2)
	
first_1, last_1:Initial and final positions of the first
    sequence. All the elements are present within a range [first_1,last_1)
first2:Initial position of the second sequence.

返回:
true, if all of the elements in both ranges match; otherwise false
// C++ program illustrating 
// use of  bool equal (InputIterator1 first1, InputIterator1 last1, 
// InputIterator2 first2) 
      
  
#include <bits/stdc++.h> 
  
int main() 
{ 
    int v1[] = { 10, 20, 30, 40, 50 }; 
    std::vector<int> vector_1 (v1, v1 + sizeof(v1) / sizeof(int) ); 
  
    // Printing vector1 
    std::cout << "Vector contains:"; 
    for (unsigned int i = 0; i < vector_1.size(); i++) 
        std::cout << " " << vector_1[i]; 
    std::cout << "\n"; 
  
    // using std::equal() 
    // Comparison within default constructor 
    if ( std::equal (vector_1.begin(), vector_1.end(), v1) ) 
        std::cout << "The contents of both sequences are equal.\n"; 
    else
        printf("The contents of both sequences differ."); 
  
}

輸出:

Vector contains: 10, 20, 30, 40, 50
The contents of both sequences are equal.

語法2:


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

first_1, last_1:Initial and final positions of the first
    sequence. All the elements are present within a range [first_1,last_1)
first2:Initial position of the second sequence.
pred:Binary function that accepts two elements as argument 
      and returns a value convertible to boolean.

返回:
true, if all of the elements in both ranges match; otherwise false
// C++ program illustrating 
// use of bool equal (InputIterator1 first1, InputIterator1 last1, 
// InputIterator2 first2, BinaryPredicate pred); 
  
#include <bits/stdc++.h> 
  
bool pred(int i, int j) 
{ 
    return (i != j); 
} 
  
int main() 
{ 
    int v1[] = { 10, 20, 30, 40, 50 }; 
    std::vector<int> vector_1 (v1, v1 + sizeof(v1) / sizeof(int) ); 
  
    // Printing vector1 
    std::cout << "Vector contains:"; 
    for (unsigned int i = 0; i < vector_1.size(); i++) 
        std::cout << " " << vector_1[i]; 
    std::cout << "\n"; 
  
    // using std::equal() 
    // Comparison based on pred 
    if ( std::equal (vector_1.begin(), vector_1.end(), v1, pred) ) 
        std::cout << "The contents of both sequences are equal.\n"; 
    else
        printf("The contents of both sequences differ."); 
  
}

輸出:

Vector contains: 10, 20, 30, 40, 50
The contents of both sequences differ.

相關文章:



相關用法


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