Top of document
©Copyright 1999 Rogue Wave Software

equal


     Algorithm

Summary

Compares two ranges for equality.

Contents

Synopsis

#include <algorithm>
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 binary_pred);

Description

The equal algorithm does a pairwise comparison of all of the elements in one range with all of the elements in another range to see if they match. The first version of equal uses the equal operator (==) as the comparison function, and the second version allows you to specify a binary predicate as the comparison function. The first version returns true if all of the corresponding elements are equal to each other. The second version of equal returns true if for each pair of elements in the two ranges, the result of applying the binary predicate is true. In other words, equal returns true if both of the following are true:

  1. There are at least as many elements in the second range as in the first;

  2. For every iterator i in the range [first1, last1) the following corresponding conditions hold:

       *i == *(first2 + (i - first1))
  3. or

       binary_pred(*i, *(first2 + (i - first1))) == true

Otherwise, equal returns false.

This algorithm assumes that there are at least as many elements available after first2 as there are in the range [first1, last1).

Complexity

equal performs at most last1-first1 comparisons or applications of the predicate.

Example

//
// equal.cpp
//
 #include <algorithm>
 #include <vector>
 #include <iostream.h>
 int main()
 {
   int d1[4] = {1,2,3,4};
   int d2[4] = {1,2,4,3};
   //
   // Set up two vectors
   //
   vector<int> v1(d1+0, d1 + 4), v2(d2+0, d2 + 4);
   // Check for equality
   bool b1 = equal(v1.begin(),v1.end(),v2.begin());
   bool b2 = equal(v1.begin(),v1.end(),
                   v2.begin(),equal_to<int>());
   // Both b1 and b2 are false
   cout << (b1 ? "TRUE" : "FALSE")  << " " 
        << (b2 ? "TRUE" : "FALSE") << endl;
   return 0;
 }
Output :
FALSE FALSE

Warnings

If your compiler does not support default template parameters then you need to always supply the Allocator template argument. For instance you'll have to write:

vector<int,allocator>

instead of:

vector<int>

Top of document