C++ 算法 中的 find_end函数

首页 / C++入门教程 / C++ 算法 中的 find_end函数

C++算法find_end()函数在集合中搜索模式的最后一次出现,或者说在集合中序列的一小部分最后一次出现。它基本上在[first1,last1)指定的参数内搜索[first2,last2)定义的序列的出现。如果找到该事件,则返回第一个元素的迭代器,否则返回last1。

find_end - 语法

template<class ForwardIterator1, classForwardIterator2>
ForwardIterator1 find_end(ForwardIterator1 first1, ForwardIterator1 last1, ForwardIterator2 first2, ForwardIterator2 last2);

template<class ForwardIterator1, class ForwardIterator2, class BinaryPredicate>
ForwardIterator1 find_end(ForwardIterator1 first1,ForwardIterator1 last1, ForwardIterator2 first2, ForwardIterator2 last2, BinaryPredicate pred);

find_end - 参数

first1 :它是参数[first1,last1)中第一个元素的正向迭代器,其中元素本身包含在参数中。

last1 :它是参数[first1,last1)中最后一个元素的前向迭代器,其中元素本身不包含在参数中。

first2 :它是参数[first2,last2)中第一个元素的正向迭代器,其中元素本身包含在参数中。

last2 :它是参数[first2,last2)中最后一个元素的前向迭代器,其中元素本身不包含在参数中。

pred :它是一个二进制函数,接受两个元素作为参数并执行该函数设计的任务。

find_end - 返回值

该函数将迭代器返回到[first1,last1)参数内最后一次出现的[first2,last2)的第一个元素。如果找不到序列,则该函数返回last1值。

find_end - 例子1

#include <iostream>     
#include <algorithm>    
#include <vector>       
bool newfunction (int m, int n) 
{
  return (m==n);
}
int main () 
{
  int newints[] = {1,2,3,4,5,1,2,3,4,5};
  std::vector<int> haystack (newints,newints+10);
  int patt1[] = {1,2,3};
  std::vector<int>::iterator ti;
  ti = std::find_end (haystack.begin(), haystack.end(), patt1, patt1+3);
  if (ti!=haystack.end())
  std::cout << "patt1 last found at position " << (ti-haystack.begin()) << '\n';
  int patt2[] = {4,5,1};
  ti = std::find_end (haystack.begin(), haystack.end(), patt2, patt2+3, newfunction);
  if (ti!=haystack.end())
  std::cout << "patt2 last found at position " << (ti-haystack.begin()) << '\n';
  return 0;
}

输出:

patt1 is last found at the position 5
patt2 is last found at the position 3

find_end - 例子2

#include<iostream>
#include<algorithm>
#include<vector>
using namespace std;
int main()
{
	vector<int>u= {1,3,10,3,10,1,3,3,10,7,8,1,3,10};
	vector<int>u1={1,3,10};
	vector<int>::iterator ti;
	ti=std::find_end(u.begin(),u.end(),u1.begin(),u1.end());
	cout<<(ti-u.begin())<<"\n";
	return 0;
} 

输出:

11

祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)

技术教程推荐

人工智能基础课 -〔王天一〕

持续交付36讲 -〔王潇俊〕

TensorFlow快速入门与实战 -〔彭靖田〕

JavaScript核心原理解析 -〔周爱民〕

性能测试实战30讲 -〔高楼〕

图解 Google V8 -〔李兵〕

徐昊 · TDD项目实战70讲 -〔徐昊〕

高并发系统实战课 -〔徐长龙〕

手把手带你写一个 MiniTomcat -〔郭屹〕

好记忆不如烂笔头。留下您的足迹吧 :)