算法之旅,直奔<algorithm>之十六 find_end

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

find_end(vs2010)

  • 引言
这是我学习总结<algorithm>的第十六篇。我是因为一个排序的实验结果,直奔<algorithm>C++库的,现在又仔细想想,我写那个排序算法,在实际当中会用自己的代码么?不会,只是能帮助自己了解的更彻底一点。
  • 作用
find_end的作用是在一段数据集合里找到可以匹配的指定一段数据集合的首地址,不过这个是从后往前找的。
  • 原型
template<class ForwardIterator1, class ForwardIterator2>
  ForwardIterator1 find_end (ForwardIterator1 first1, ForwardIterator1 last1,
                             ForwardIterator2 first2, ForwardIterator2 last2)
{
  if (first2==last2) return last1;  // specified in C++11

  ForwardIterator1 ret = last1;

  while (first1!=last1)
  {
    ForwardIterator1 it1 = first1;
    ForwardIterator2 it2 = first2;
    while (*it1==*it2) {    // or: while (pred(*it1,*it2)) for version (2)
        ++it1; ++it2;
        if (it2==last2) { ret=first1; break; }
        if (it1==last1) return ret;
    }
    ++first1;
  }
  return ret;
}
  • 实验
数据集合如下

匹配{1,2,3} ,返回的是第二个1的地址,
匹配{4,5,1},返回的是第一个4的地址。
  • 代码
test.cpp
#include <iostream>     // std::cout
#include <algorithm>    // std::find_end
#include <vector>       // std::vector

bool myfunction (int i, int j) 
{
	return (i==j);
}

int main () {
	int myints[] = {1,2,3,4,5,1,2,3,4,5};
	std::vector<int> haystack (myints,myints+10);

	int needle1[] = {1,2,3};

	// using default comparison:
	std::vector<int>::iterator it;
	it = std::find_end (haystack.begin(), haystack.end(), needle1, needle1+3);

	if (it!=haystack.end())
		std::cout << "needle1 last found at position " << (it-haystack.begin()) << '\n';

	int needle2[] = {4,5,1};

	// using predicate comparison:
	it = std::find_end (haystack.begin(), haystack.end(), needle2, needle2+3, myfunction);

	if (it!=haystack.end())
		std::cout << "needle2 last found at position " << (it-haystack.begin()) << '\n';
	system("pause");
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值