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
順向迭代器,定址要搜尋之範圍中第一個項目的位置。_Last1
順向迭代器,定址要搜尋之範圍中越過最後一個項目的位置。_First2
解決向前 Iterator 的第一個項目位置範圍相符。_Last2
解決的 Iterator 向前到最後的項目位置的範圍相符。_Comp
使用者定義的述詞函式物件定義將內容的情況下,如果兩個項目要採用視為相等。 符合時,二進位述詞會採用兩個引數並傳回 true ,不符合時則傳回 false。
傳回值
解決向前 Iterator 的第一 subsequence 的第一個項目位置二進位述詞實際上就相當於指定的比對指定的序列或。
備註
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