c++ std標準庫 演算法<algorithm> 查詢最後位置 find_end()
阿新 • • 發佈:2020-12-19
技術標籤:# 4.1 C++c++演算法algorithmfind_end
std::find_end
簡介:
在序列 A 中查詢序列 B 最後一次出現的位置。
函式原型
equality (1) template <class ForwardIterator1, class ForwardIterator2>
ForwardIterator1 find_end (ForwardIterator1 first1, ForwardIterator1 last1, ForwardIterator2 first2, ForwardIterator2 last2);
predicate ( 2) template <class ForwardIterator1, class ForwardIterator2, class BinaryPredicate>
ForwardIterator1 find_end (ForwardIterator1 first1, ForwardIterator1 last1, ForwardIterator2 first2, ForwardIterator2 last2, BinaryPredicate pred);
官方手冊
http://www.cplusplus.com/reference/algorithm/find_end/
使用示例:
#include <functional>
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
template <class T>
void FillValue(T& vect, int first, int last)
{
if (last >= first)
{
for (int i = first; i <= last; ++i)
vect.insert(vect.end(), i) ;
}
else
{
cout << " The indexes is error: last < first. " << endl;
}
}
void print(int elem)
{
cout << elem << " ";
}
void main()
{
vector <int> myvector;
vector <int> subvector;
FillValue(myvector, -3, 12);
FillValue(myvector, -3, 6);
FillValue(subvector, -1, 3);
for_each(myvector.begin(), myvector.end(), print);
cout << endl;
for_each(subvector.begin(), subvector.end(), print);
cout << endl;
vector<int>::iterator pos1;
// pos1=find_first_of(myvector.begin(),myvector.end(),subvector.begin(),subvector.end());
pos1 = find_end(myvector.begin(), myvector.end(), subvector.begin(), subvector.end());
if (pos1 != myvector.end())
{
// cout<<"第一個子串在原串中的位置: "<<distance(myvector.begin(),pos1)+1<<endl;
cout << "最後一個子區間在原串中的位置: " << distance(myvector.begin(), pos1) + 1 << endl;
}
else
{
cout << "沒有搜尋到需要的子串." << endl;
}
vector<int>::reverse_iterator rpos;
rpos=find_first_of(myvector.rbegin(),myvector.rend(),subvector.begin(),subvector.end());
cout<<"原串中最後一個字串的位置: "<<distance(myvector.begin(),rpos.base())<<endl;
}