算法之旅,直奔<algorithm>之十一 equal

35 篇文章 1 订阅
29 篇文章 0 订阅

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.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;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值