equal(vs2010)
- 引言
这是我学习总结
<algorithm>的第十一篇,equal功能还是蛮强大的,正如你理解的一样。
- 作用
equal的作用是检测一段连续地址的数据是否和另一段连续地址的数据是否一样。当然也可以自定义比较的条件,例如相差n等等。
In English,that is to
Test whether the elements in two ranges are equal
Compares the elements in the range
[first1,last1)
with those in the range beginning at
first2, and returns
true
if all of the elements in both ranges match.
- 原理
template <class InputIterator1, class InputIterator2>
bool equal ( InputIterator1 first1, InputIterator1 last1, InputIterator2 first2 )
{
while (first1!=last1) {
if (!(*first1 == *first2)) // or: if (!pred(*first1,*first2)), for version 2
return false;
++first1; ++first2;
}
return true;
}
- 实验
例如,myints 是一个数组,myvector是一个容器,他俩的元素一样,则返回true。
将 myvector[3]=81,那么myvector: 20 40 60 81 100。这时候再次判断就不一样了。
请看程序结果
- 代码
Test whether the elements in two ranges are equal
Compares the elements in the range
[first1,last1)
with those in the range beginning at
first2, and returns
true
if all of the elements in both ranges match.
template <class InputIterator1, class InputIterator2>
bool equal ( InputIterator1 first1, InputIterator1 last1, InputIterator2 first2 )
{
while (first1!=last1) {
if (!(*first1 == *first2)) // or: if (!pred(*first1,*first2)), for version 2
return false;
++first1; ++first2;
}
return true;
}
test.cpp
#include <iostream> // std::cout
#include <algorithm> // std::equal
#include <vector> // std::vector
bool mypredicate (int i, int j) {
return (i==j);
}
int main () {
int myints[] = {20,40,60,80,100}; // myints: 20 40 60 80 100
std::vector<int>myvector (myints,myints+5); // myvector: 20 40 60 80 100
// using default comparison:
if ( std::equal (myvector.begin(), myvector.end(), myints) )
std::cout << "The contents of both sequences are equal.\n";
else
std::cout << "The contents of both sequences differ.\n";
myvector[3]=81; // myvector: 20 40 60 81 100
// using predicate comparison:
if ( std::equal (myvector.begin(), myvector.end(), myints, mypredicate) )
std::cout << "The contents of both sequences are equal.\n";
else
std::cout << "The contents of both sequences differ.\n";
system("pause");
return 0;
}