posts - 1,  comments - 0,  trackbacks - 0
          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 憤怒的考拉 閱讀(191) 評論(0)  編輯  收藏

          只有注冊用戶登錄后才能發表評論。


          網站導航:
           
          <2025年6月>
          25262728293031
          1234567
          891011121314
          15161718192021
          22232425262728
          293012345

          常用鏈接

          留言簿

          隨筆檔案

          文章檔案

          搜索

          •  

          最新評論

          主站蜘蛛池模板: 宾川县| 巍山| 津南区| 惠安县| 高邮市| 祥云县| 隆昌县| 六枝特区| 达拉特旗| 成都市| 台南县| 蕉岭县| 琼海市| 陕西省| 邛崃市| 永兴县| 通化市| 务川| 南郑县| 金乡县| 舒城县| 富川| 桑植县| 凤台县| 金川县| 徐汇区| 当雄县| 五原县| 施秉县| 锡林浩特市| 博客| 黄石市| 镇坪县| 公主岭市| 阳江市| 乡城县| 中宁县| 台北市| 河曲县| 武清区| 沙雅县|