find()函數的偽代碼如下:
template<class InputIterator, class T>
InputIterator find ( InputIterator first, InputIterator last, const T& value )
{
for ( ;first!=last; first++) if ( *first==value ) break;
return first;
}
一般第一個參數是迭代器的起始位置,第二參數是迭代器的結束位置,第三個參數是要查找的參數。當然參數也可以是數組名或者指針。如下所示:
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
int main () {
int myints[] = { 10, 20, 30 ,40 };
int * p;
// pointer to array element:
p = find(myints,myints+4,30);
++p;
cout << "The element following 30 is " << *p << endl;
vector<int> myvector (myints,myints+4);
vector<int>::iterator it;
// iterator to vector element:
it = find (myvector.begin(), myvector.end(), 30);
++it;
cout << "The element following 30 is " << *it << endl;
return 0;
}
接收函數返回值的是一個地址值或者同類型的迭代器。區分string類的find()函數。
通過it==myvector.end()來判斷是否找到此值,相等說明沒找到。
補充一例:
泛型算法find的使用(必須包含頭文件algorithm)
2011-01-13 17:11
#include<iostream> #include <algorithm>//使用泛型算法必須包含頭文件algorithm #include<vector> #include<string> using namespace std; int main() { vector<int> ivec; while(true) { cout<<"continue?no(0) yes-enter an int value(not 0):"<<endl; int val; cin>>val; if(val==0) break; else ivec.push_back(val); } cout<<"please enter int value what you want to find:"<<endl; int ival; cin>>ival; vector<int>::const_iterator cit=find(ivec.begin(),ivec.end(),ival);//find算法是在algorithm中定義的 cout<<"what you find "<<ival<<(cit==ivec.end()? " is not find" : " found")<<endl; return 0; } |
刪除容器的操作可見C++primer第四版的9.3.7。
posted on 2012-04-04 13:23
憤怒的考拉 閱讀(189)
評論(0) 編輯 收藏