<algorithm>
头文件中,常用于在序列 A 中查找序列 B 最后一次出现的位置。例如,有如下 2 个序列:
序列 A:1,2,3,4,5,1,2,3,4,5
序列 B:1,2,3
//查找序列 [first1, last1) 中最后一个子序列 [first2, last2) ForwardIterator find_end (ForwardIterator first1, ForwardIterator last1, ForwardIterator first2, ForwardIterator last2); //查找序列 [first2, last2) 中,和 [first2, last2) 序列满足 pred 规则的最后一个子序列 ForwardIterator find_end (ForwardIterator first1, ForwardIterator last1, ForwardIterator first2, ForwardIterator last2, BinaryPredicate pred);其中,各个参数的含义如下:
#include <iostream> // std::cout #include <algorithm> // std::find_end #include <vector> // std::vector using namespace std; //以普通函数的形式定义一个匹配规则 bool mycomp1(int i, int j) { return (i%j == 0); } //以函数对象的形式定义一个匹配规则 class mycomp2 { public: bool operator()(const int& i, const int& j) { return (i%j == 0); } }; int main() { vector<int> myvector{ 1,2,3,4,8,12,18,1,2,3 }; int myarr[] = { 1,2,3 }; //调用第一种语法格式 vector<int>::iterator it = find_end(myvector.begin(), myvector.end(), myarr, myarr + 3); if (it != myvector.end()) { cout << "最后一个{1,2,3}的起始位置为:" << it - myvector.begin() << ",*it = " << *it << endl; } int myarr2[] = { 2,4,6 }; //调用第二种语法格式 it = find_end(myvector.begin(), myvector.end(), myarr2, myarr2 + 3, mycomp2()); if (it != myvector.end()) { cout << "最后一个{2,3,4}的起始位置为:" << it - myvector.begin() << ",*it = " << *it; } return 0; }程序执行结果为:
匹配{1,2,3}的起始位置为:7,*it = 1
匹配{2,3,4}的起始位置为:4,*it = 8
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; }
本文链接:http://task.lmcjl.com/news/13171.html