避免编写技巧性很高代码
1 #include <iostream> 2 #include <algorithm> 3 #include <vector> 4 #include <list> 5 #include <set> 6 #define size 10 7 8 /* run this program using the console pauser or add your own getch, system("pause") or input loop */ 9 10 using namespace std; 11 12 //产生指定范围的整数随机数 13 int getrand(int min,int max) { 14 int m; 15 m=(max-min); 16 m=min+double(rand())/RAND_MAX*m ; 17 return m; 18 } 19 20 //利用类模板生成实例 21 typedef vector < int > IntArray; 22 typedef list <int> LISTINT; 23 typedef set<int> SET_INT; 24 25 //在main()函数中测试accumulate算法 26 int main(int argc, char** argv) { 27 { 28 //-------------------------------------------- 29 // count算法对于普通数组的计算 30 //--------------------------------------------- 31 int x[size]; 32 33 cout<<"x[]:"; 34 for (int i=0;i<size;i++) { 35 x[i]=getrand(1,3); 36 cout<<x[i]<<" "; 37 } 38 cout<<endl; 39 cout<<"count(x,x+size,2)="; 40 cout<<count(x,x+size,2)<<endl; 41 cout<<"count(x+2,x+8,2)="; 42 cout<<count(x+2,x+8,2)<<endl; 43 //-------------------------------------------- 44 // count算法对于vector容器的计算 45 //--------------------------------------------- 46 //声明intvector容器和迭代器ii 47 IntArray intvector; 48 IntArray::iterator ii; 49 50 //向intvector容器中插入元素 51 for (int i=1; i<size; i++) { 52 intvector.push_back(getrand(2,6)); 53 }; 54 //显示intvector容器中的元素值和统计结果 55 cout << "intvector: "; 56 for (ii=intvector.begin();ii !=intvector.end();++ii) 57 cout<<(*ii)<<" "; 58 cout<<endl; 59 cout<<"count(intvector.begin(),intvector.end(),4)="; 60 cout<<count(intvector.begin(),intvector.end(),4)<<endl; 61 //-------------------------------------------- 62 // count算法对于list容器的计算 63 //--------------------------------------------- 64 //声明list容器对象和迭代器 65 LISTINT::iterator iL; 66 LISTINT list1; 67 68 //向list1容器对象中插入元素并显示 69 for (int i=1; i<size; i++) { 70 list1.push_front(getrand(3,5)); 71 }; 72 73 //显示list1容器的元素值和统计结果 74 cout << "list1: "; 75 for (iL=list1.begin();iL !=list1.end();++iL) 76 cout<<(*iL)<<" "; 77 cout<<endl; 78 cout<<"count(list1.begin(),list1.end(),3)="; 79 cout<<count(list1.begin(),list1.end(),3)<<endl; 80 //-------------------------------------------- 81 // count算法对于set容器的计算 82 //--------------------------------------------- 83 //声明set容器对象和迭代器 84 SET_INT set1; 85 SET_INT::iterator si; 86 87 //向set1容器中插入元素 88 for (int i=1; i<size; i++) { 89 set1.insert(getrand(1,10)); 90 }; 91 92 //显示set1容器的元素值和统计结果 93 cout <<"set1: "; 94 for (si=set1.begin();si !=set1.end();++si) 95 cout<<(*si)<<" "; 96 cout<<endl; 97 cout<<"count(set1.begin(),set1.end(),5)="; 98 cout<<count(set1.begin(),set1.end(),5)<<endl; 99 100 return 0; 101 102 } 103 }