C ++ STL algorithm is equal to

One particularly useful standard algorithm is std::equal , which is defined as follows:

 template <typename InputIterator1, typename InputIterator2> inline bool equal(InputIterator1 start1, InputIterator1 end1, InputIterator2 start2) { while(start1 != end1) { if(*start1 != *start2) return false; ++start1; ++start2; } return true; } 

The algorithm traverses the range defined by [start1, end1) and [start2, start2 + (end1 – start1)) and returns whether the elements in the range are equal. Note that the algorithm is templated by two different types of input iterators.

Why is this?

+8
c ++ equals algorithm stl
source share
3 answers

Suppose you have std::list<int> and std::vector<int> and you want to know if they are equal. If std::equal did not use different types of iterators, you could not use it, since std::list<int>::iterator not the same type as std::vector<int>::iterator .

This also applies to the same type of container, but stores different elements. A std::vector<int>::iterator is not the same as std::vector<long long>::iterator , and therefore you cannot compare them if it used the same type for both pairs of iterators.

+12
source share

So far, you have received two answers about containers. This is the wrong trick. Fundamental data abstraction in STL is a sequence . The sequence is determined by a pair of iterators. Containers are one way to manage sequences, but this is not the only way. So, to give the answer right <g>:

std::equal compares two sequences for equality. There is no reason to limit the use of the algorithm to sequences having the same type of iterator, so there is no such limit. Sequences can have a different origin and can refer to different types of values.

For example, you can check whether the values ​​represented in a file that contains a textual representation of double values ​​match the contents of a vector of integers stored in memory. A vector defines a sequence; you can get begin() and end() on your iterators. The file defines the sequence; you can get its iterators by opening the file with ifstream and creating a pair of istream_iterator<double> objects. std::equal (and all other standard algorithms) will work fine with these disparate data sources and their various data types.

+8
source share

This is templated so that you can pass either two iterators of the same type, or two iterators with different types.



For example:

 vector<int> a; //some stuff list<int> b; //some stuff equal(a.begin(), a.end(), b.begin()); /* Here InputIterator1 is a vector<int>::iterator and InputIterator2 is a list<int>::iterator */ vector<double> c; //some stuff vector<double> d; //some stuff equal(c.begin(), c.end(), d.begin()); /* Here InputIterator1 is a vector<double>::iterator and InputIterator2 is also a vector<double>::iterator */ 
+5
source share

All Articles