STL中的equal函数:
template<class InputIterator1, class InputIterator2> bool equal( InputIterator1 _First1, InputIterator1 _Last1, InputIterator2 _First2 ); template<class InputIterator1, class InputIterator2, class BinaryPredicate> bool equal( InputIterator1 _First1, InputIterator1 _Last1, InputIterator2 _First2, BinaryPredicate _Comp );
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 // alg_equal.cpp 2 // compile with: /EHsc 3 #include <vector> 4 #include <algorithm> 5 #include <iostream> 6 7 // Return whether second element is twice the first 8 bool twice ( int elem1, int elem2 ) 9 { 10 return elem1 * 2 == elem2; 11 } 12 13 int main( ) 14 { 15 using namespace std; 16 vector <int> v1, v2, v3; 17 vector <int>::iterator Iter1, Iter2, Iter3; 18 19 int i; 20 for ( i = 0 ; i <= 5 ; i++ ) 21 { 22 v1.push_back( 5 * i ); 23 } 24 25 int ii; 26 for ( ii = 0 ; ii <= 5 ; ii++ ) 27 { 28 v2.push_back( 5 * ii ); 29 } 30 31 int iii; 32 for ( iii = 0 ; iii <= 5 ; iii++ ) 33 { 34 v3.push_back( 10 * iii ); 35 } 36 37 cout << "v1 = ( " ; 38 for ( Iter1 = v1.begin( ) ; Iter1 != v1.end( ) ; Iter1++ ) 39 cout << *Iter1 << " "; 40 cout << ")" << endl; 41 42 cout << "v2 = ( " ; 43 for ( Iter2 = v2.begin( ) ; Iter2 != v2.end( ) ; Iter2++ ) 44 cout << *Iter2 << " "; 45 cout << ")" << endl; 46 47 cout << "v3 = ( " ; 48 for ( Iter3 = v3.begin( ) ; Iter3 != v3.end( ) ; Iter3++ ) 49 cout << *Iter3 << " "; 50 cout << ")" << endl; 51 52 // Testing v1 and v2 for equality under identity 53 bool b; 54 b = equal( v1.begin( ), v1.end( ), v2.begin( ) ); 55 56 if ( b ) 57 cout << "The vectors v1 and v2 are equal under equality." 58 << endl; 59 else 60 cout << "The vectors v1 and v2 are not equal under equality." 61 << endl; 62 63 // Testing v1 and v3 for equality under identity 64 bool c; 65 c = equal( v1.begin( ), v1.end( ), v3.begin( ) ); 66 67 if ( c ) 68 cout << "The vectors v1 and v3 are equal under equality." 69 << endl; 70 else 71 cout << "The vectors v1 and v3 are not equal under equality." 72 << endl; 73 74 // Testing v1 and v3 for equality under twice 75 bool d; 76 d = equal( v1.begin( ), v1.end( ), v3.begin( ), twice ); 77 78 if ( d ) 79 cout << "The vectors v1 and v3 are equal under twice." 80 << endl; 81 else 82 cout << "The vectors v1 and v3 are not equal under twice." 83 << endl; 84 } 85 86 /* 87 Output 88 89 v1 = ( 0 5 10 15 20 25 ) 90 v2 = ( 0 5 10 15 20 25 ) 91 v3 = ( 0 10 20 30 40 50 ) 92 The vectors v1 and v2 are equal under equality. 93 The vectors v1 and v3 are not equal under equality. 94 The vectors v1 and v3 are equal under twice. 95 */