c++ std標準庫 演算法<algorithm> 查詢第一次出現的位置 find_first_of()
阿新 • • 發佈:2020-12-19
技術標籤:# 4.1 C++c++find_first_of
std::find_first_of
簡介:
查詢第一次出現的位置。
函式原型
//以判斷兩者相等作為匹配規則
equality (1) template <class InputIterator, class ForwardIterator>
InputIterator find_first_of (InputIterator first1, InputIterator last1, ForwardIterator first2, ForwardIterator last2);
//以 pred 作為匹配規則
predicate (2) template <class InputIterator, class ForwardIterator, class BinaryPredicate>
InputIterator find_first_of (InputIterator first1, InputIterator last1, ForwardIterator first2, ForwardIterator last2, BinaryPredicate pred);
官方手冊
http://www.cplusplus.com/reference/algorithm/find_first_of/
使用示例:
#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());
if (pos1 != myvector.end())
{
cout << "第一個子串在原串中的位置: " << distance(myvector.begin(), pos1) + 1 << endl;
}
else
{
cout << "沒有搜尋到需要的子串." << endl;
}
}