不要设计面面俱到、非常灵活的数据结构。
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 }
原文地址:https://www.cnblogs.com/borter/p/9418292.html
时间: 2024-10-18 23:20:13