C++算法search()函数在参数[first1,last1)中搜索由参数[first2,last2)定义的子序列的出现,然后返回第一个元素的迭代器。如果子序列不存在,则返回last1的迭代器。
template<class ForwardIterator1, class ForwardIterator2> ForwardIterator1 search (ForwardIterator1 first1, ForwardIterator last1, ForwardIterator2 first2, ForwardIterator2 last2); template<class ForwardIterator1, class ForwardIterator2, class BinaryPredicate> ForwardIterator1 search(ForwardIterator1 first1, ForwardIterator1 last1, ForwardIterator2 first2, ForwardIterator2 last2, BinaryPredicate pred);
first1 :它是[first1,last1)的第一个元素的正向迭代器。
last1 :它是[first1,last1)的最后一个元素的正向迭代器。
first2 :它是[first2,last2)的第一个元素的正向迭代器。
pred :它是一个二进制函数,接受两个元素作为参数并执行该函数设计的任务。
该函数将迭代器返回到第一次出现的子序列的第一个元素,否则返回last1元素。
#include <iostream> #include <algorithm> #include <vector> bool newpredicate (int m, int n) { return (m==n); } int main () { std::vector<int> haystack; for (int a=1; a<10; a++) haystack.push_back(a*10); int patt1[] = {20,30,40,50}; std::vector<int>::iterator ti; ti = std::search (haystack.begin(), haystack.end(), patt1, patt1+4); if (ti!=haystack.end()) std::cout << "patt1 found at position " << (ti-haystack.begin()) << '\n'; else std::cout << "patt1 not found\n"; int patt2[] = {40,35,50}; ti = std::search (haystack.begin(), haystack.end(), patt2, patt2+3, newpredicate); if (ti!=haystack.end()) std::cout << "patt2 found at position " << (ti-haystack.begin()) << '\n'; else std::cout << "patt2 not found\n"; return 0; }
输出:
patt1 found at position 1 patt2 not found
#include<iostream> #include<vector> #include<algorithm> using namespace std; int main() { int m, n; vector <int> u1={1,2,3,4,5,6,7}; vector <int> u2={3,4,5}; vector<int>::iterator ti; ti = std::search(u1.begin(), u1.end(), u2.begin(),u2.end()); if(ti!=u1.end()) { cout<<"Vector2 is present at index:"<<(ti-u1.begin()); } else { cout<<"In vector1, vector2 is not present"; } return 0; }
输出:
Vector2 is present at index:2
祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)