1. 程式人生 > >不要設計面面俱到、非常靈活的數據結構

不要設計面面俱到、非常靈活的數據結構

fir col har class tchar star iostream style gin

不要設計面面俱到、非常靈活的數據結構。

 1 #include <iostream>
 2 #include <iostream>
 3 #include <algorithm>
 4 #include <string>
 5 #include <vector>
 6 /* run this program using the console pauser or add your own getch, system("pause") or input loop */
 7 
 8 using namespace std;
 9 
10
//如果字符串以‘S‘開頭,則返回true 11 int MatchFirstChar( const string& str) 12 { 13 string s("S") ; 14 return s == str.substr(0,1) ; 15 } 16 17 //測試count_if算法 18 int main(int argc, char** argv) { 19 { 20 const int VECTOR_SIZE = 8 ; 21 22 //生成成員類型為strings的vector容器類 23 typedef vector<string > StringVector ;
24 25 //定義叠代器類型 26 typedef StringVector::iterator StringVectorIt ; 27 28 //聲明vector容器的對象 29 StringVector NamesVect(VECTOR_SIZE) ; 30 31 //聲明叠代器 32 StringVectorIt start, end,it; 33 34 int result = 0 ; // 存放統計數據 35 36 //初始化vector容器NamesVect 37 NamesVect[0] = "She" ; 38
NamesVect[1] = "Sells" ; 39 NamesVect[2] = "Sea" ; 40 NamesVect[3] = "Shells" ; 41 NamesVect[4] = "by" ; 42 NamesVect[5] = "the" ; 43 NamesVect[6] = "Sea" ; 44 NamesVect[7] = "Shore" ; 45 46 //設置容器的起始位置和終止位置 47 start = NamesVect.begin() ; 48 end = NamesVect.end() ; 49 50 //顯示NamesVect容器的元素 51 cout << "NamesVect: " ; 52 for(StringVectorIt it = start; it != end; it++) 53 cout << *it << " " ; 54 cout <<endl ; 55 56 //統計並顯示NamesVect容器的所有元素中以‘S‘字符開頭的字符串 57 result = count_if(start, end, MatchFirstChar) ; 58 cout << "Number of elements that start with letter \"S\" = " 59 << result << endl ; 60 61 //顯示NamesVect容器[1,6]之間的元素 62 cout <<"NamesVect[1]--NamesVect[6]: " ; 63 for( it = &NamesVect[1]; it != &NamesVect[7]; it++) 64 cout << *it << " " ; 65 cout <<endl ; 66 67 //統計並顯示NamesVect容器的所有元素中以‘S‘字符開頭的字符串 68 result = count_if(&NamesVect[1], &NamesVect[7], MatchFirstChar) ; 69 cout << "Number of elements that start with letter \"S\" = " 70 << result << endl ; 71 72 return 0; 73 }

不要設計面面俱到、非常靈活的數據結構