search
搜尋一個序列的第一個會在二進位述詞實際上就相當於指定的項目與相等項目特定順序或項目與項目在指定的序列的目標範圍內。
template<class ForwardIterator1, class ForwardIterator2>
ForwardIterator1 search(
ForwardIterator1 _First1,
ForwardIterator1 _Last1,
ForwardIterator2 _First2,
ForwardIterator2 _Last2
);
template<class ForwardIterator1, class ForwardIterator2, class Predicate>
ForwardIterator1 search(
ForwardIterator1 _First1,
ForwardIterator1 _Last1,
ForwardIterator2 _First2,
ForwardIterator2 _Last2
Predicate _Comp
);
參數
_First1
處理順向 Iterator 的第一個項目的位置會搜尋的範圍。_Last1
處理順向的 Iterator 超過最後一個項目的位置是在要搜尋的範圍。_First2
處理順向Iterator的第一個項目的位置在要對應的範圍。_Last2
處理順向的Iterator超過最後一個項目的位置是在要對應的範圍。_Comp
定義要滿足條件的使用者定義之述詞函式物件,如果兩個項目將會視為相等。一個二進位述詞採用兩個引數並傳回 true ,當內容和 false ,則內容。
傳回值
處理順向 Iterator 的第一個序列的第一個項目位置一類的二進位述詞實際上就相當於指定的符合指定的序列或。
備註
用來 operator== 判斷在項目和指定值之間的比對必須強制在其運算元之間的一個層級的關聯性。
參考的範圍必須是有效的,任何指標必須 dereferenceable,而且每一個序列中最後一個位置開始可取得的會增加。
平均複雜度是線性主要於搜尋範圍的大小,因此,最壞情況複雜也是線性主要套用至序列的大小會搜尋。
範例
// alg_search.cpp
// compile with: /EHsc
#include <vector>
#include <list>
#include <algorithm>
#include <iostream>
// Return whether second element is twice the first
bool twice (int elem1, int elem2 )
{
return 2 * elem1 == elem2;
}
int main( ) {
using namespace std;
vector <int> v1, v2;
list <int> L1;
vector <int>::iterator Iter1, Iter2;
list <int>::iterator L1_Iter, L1_inIter;
int i;
for ( i = 0 ; i <= 5 ; i++ )
{
v1.push_back( 5 * i );
}
for ( i = 0 ; i <= 5 ; i++ )
{
v1.push_back( 5 * i );
}
int ii;
for ( ii = 4 ; ii <= 5 ; ii++ )
{
L1.push_back( 5 * ii );
}
int iii;
for ( iii = 2 ; iii <= 4 ; iii++ )
{
v2.push_back( 10 * iii );
}
cout << "Vector v1 = ( " ;
for ( Iter1 = v1.begin( ) ; Iter1 != v1.end( ) ; Iter1++ )
cout << *Iter1 << " ";
cout << ")" << endl;
cout << "List L1 = ( " ;
for ( L1_Iter = L1.begin( ) ; L1_Iter!= L1.end( ) ; L1_Iter++ )
cout << *L1_Iter << " ";
cout << ")" << endl;
cout << "Vector v2 = ( " ;
for ( Iter2 = v2.begin( ) ; Iter2 != v2.end( ) ; Iter2++ )
cout << *Iter2 << " ";
cout << ")" << endl;
// Searching v1 for first match to L1 under identity
vector <int>::iterator result1;
result1 = search (v1.begin( ), v1.end( ), L1.begin( ), L1.end( ) );
if ( result1 == v1.end( ) )
cout << "There is no match of L1 in v1."
<< endl;
else
cout << "There is at least one match of L1 in v1"
<< "\n and the first one begins at "
<< "position "<< result1 - v1.begin( ) << "." << endl;
// Searching v1 for a match to L1 under the binary predicate twice
vector <int>::iterator result2;
result2 = search (v1.begin( ), v1.end( ), v2.begin( ), v2.end( ), twice );
if ( result2 == v1.end( ) )
cout << "There is no match of L1 in v1."
<< endl;
else
cout << "There is a sequence of elements in v1 that "
<< "are equivalent\n to those in v2 under the binary "
<< "predicate twice\n and the first one begins at position "
<< result2 - v1.begin( ) << "." << endl;
}
需求
標題: <algorithm>
命名空間: std