1. 程式人生 > >盡量使用標準庫函數

盡量使用標準庫函數

this add style find() return stream nta oop arr

盡量使用標準庫函數,不要“發明”已經存在的庫函數。

 1 #include <iostream>
 2 #include <algorithm>
 3 #include <vector>
 4 #define ARRAY_SIZE 10
 5 /* run this program using the console pauser or add your own getch, system("pause") or input loop */
 6 
 7 using namespace std;
 8 
 9 //利用類模板生成實例
10 typedef vector < int
> IntArray; 11 12 //顯示數組 13 void put_array(int x[],int size) { 14 for(int i=0;i<size;i++) 15 cout<<x[i]<<" "; 16 } 17 18 //顯示vector容器中的元素 19 void put_vector(IntArray v) 20 { 21 IntArray::iterator theIterator; 22 23 for (theIterator=v.begin();theIterator!=v.end();++theIterator){
24 cout<<(*theIterator)<<" "; 25 } 26 } 27 28 //在main()函數中測試find()_end()算法 29 int main(int argc, char** argv) { 30 { 31 //-------------------------------------------- 32 // find_end()算法對普通數組的處理 33 //--------------------------------------------- 34 int x[ARRAY_SIZE]={1,3,5,7,9,2
,4,6,8,10}; 35 cout << "x[]: "; 36 put_array(x,ARRAY_SIZE); 37 cout<<endl; 38 int y[]={5,7,9}; 39 cout << "y[]: "; 40 put_array(y,3); 41 cout<<endl; 42 43 // find_end()算法查找,並顯示查找結果 44 int *p=find_end(x,x+ARRAY_SIZE,&y[0],&y[2]); 45 if (p != x + ARRAY_SIZE) { //查到 46 cout << "The first element that matches :" ; 47 put_array(y,3); 48 cout<< " is at location in x" << p - x<< endl; 49 } 50 else { //未查到 51 cout << "The sequence does not contain any elements"; 52 cout<< " with value " ; 53 put_array(&x[3],3); 54 } 55 56 //-------------------------------------------- 57 // find_end()算法對vector容器的處理 58 //--------------------------------------------- 59 //聲明intvector容器對象 60 IntArray intvector; 61 62 //向intvector容器中插入元素 63 for (int i=1; i<=10; i++) { 64 intvector.push_back(i); 65 }; 66 67 //顯示intvector容器中的元素值 68 cout << "intvector: "; 69 put_vector(intvector); 70 cout<<endl; 71 72 IntArray temp; 73 temp.push_back(5); 74 temp.push_back(6); 75 temp.push_back(7); 76 cout << "temp: "; 77 put_vector(temp); 78 cout<<endl; 79 80 // find_end()算法查找,並顯示查找結果 81 IntArray::iterator pos; 82 pos=find_end(intvector.begin(),intvector.end(),temp.begin(),temp.end()); 83 84 if (pos != intvector.end()) { //查到 85 cout << "The first element that matches "; 86 put_vector(temp); 87 cout<< " is at location in intvector " <<pos - intvector.begin()<< endl; 88 } 89 else { //未查到 90 cout << "The sequence does not contain any elements"; 91 cout<< " with value "; 92 put_vector(temp); 93 cout<< endl ; 94 } 95 return 0; 96 } 97 }

盡量使用標準庫函數