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 元素。
例子1
#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
例子2
#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
複雜度
該函數從 first1 元素到 last1 元素具有線性複雜度。
數據競爭
訪問兩個範圍內的對象。
異常
如果任何參數拋出異常,該函數將拋出異常。
相關用法
- C++ search_n()用法及代碼示例
- C++ set rbegin()用法及代碼示例
- C++ set upper_bound()用法及代碼示例
- C++ set swap()用法及代碼示例
- C++ set::rbegin()、set::rend()用法及代碼示例
- C++ set size()用法及代碼示例
- C++ set lower_bound()用法及代碼示例
- C++ set::begin()、set::end()用法及代碼示例
- C++ set erase()用法及代碼示例
- C++ set find()用法及代碼示例
- C++ set end()用法及代碼示例
- C++ set cbegin()用法及代碼示例
- C++ set key_comp()用法及代碼示例
- C++ set equal_range()用法及代碼示例
- C++ set::lower_bound()用法及代碼示例
- C++ set::erase()用法及代碼示例
- C++ set rend()用法及代碼示例
- C++ set::size()用法及代碼示例
- C++ set clear()用法及代碼示例
- C++ set begin()用法及代碼示例
注:本文由純淨天空篩選整理自 C++ Algorithm Function search()。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。