当心文件 I/O 有错误。
1 #include <iostream> 2 #include <iostream> 3 #include <numeric> 4 #include <vector> 5 #include <list> 6 #include <set> 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 typedef vector < int > IntArray; 14 typedef list <int> LISTINT; 15 typedef set<int> SET_INT; 16 int add(int a, int b) { 17 return a+b; 18 } 19 //在main()函数中测试accumulate算法 20 int main(int argc, char** argv) { 21 { 22 //-------------------------------------------- 23 // accumulate算法对于普通数组的计算 24 //--------------------------------------------- 25 int x[]={1,3,5,7,9}; 26 27 cout<<"x[]:"; 28 for (int i=0;i<5;i++) 29 cout<<x[i]<<" "; 30 cout<<endl; 31 cout<<"accumulate(x,x+5,0)="; 32 cout<<accumulate(x,x+5,0)<<endl; 33 int val=100; 34 cout<<"val="<<val<<endl; 35 cout<<"accumulate(x,x+5,val)="; 36 cout<<accumulate(x,x+5,val)<<endl; 37 //-------------------------------------------- 38 // accumulate算法对于vector容器的计算 39 //--------------------------------------------- 40 //声明intvector容器和迭代器ii 41 IntArray intvector; 42 IntArray::iterator ii; 43 44 //向intvector容器中插入元素 45 for (int i=1; i<=5; i++) { 46 intvector.push_back(i); 47 }; 48 49 //显示intvector容器中的元素值和累加结果 50 cout << "intvector: "<<endl; 51 for (ii=intvector.begin();ii !=intvector.end();++ii) 52 cout<<(*ii)<<" "; 53 cout<<endl; 54 cout<<"accumulate(intvector.begin(),intvector.end(),0)="; 55 cout<<accumulate(intvector.begin(),intvector.end(),0)<<endl; 56 //-------------------------------------------- 57 // accumulate算法对于list容器的计算 58 //--------------------------------------------- 59 //声明list容器对象和迭代器 60 LISTINT::iterator iL; 61 LISTINT list1; 62 63 //向list1容器对象中插入元素并显示 64 list1.push_front(1); 65 list1.push_front(3); 66 list1.push_front(5); 67 list1.push_back(2); 68 list1.push_back(6); 69 70 //显示list1容器的元素值和累加结果 71 cout << "list1: "<<endl; 72 for (iL=list1.begin();iL !=list1.end();++iL) 73 cout<<(*iL)<<" "; 74 cout<<endl; 75 cout<<"accumulate(list1.begin(),list1.end(),0)="; 76 cout<<accumulate(list1.begin(),list1.end(),0)<<endl; 77 //-------------------------------------------- 78 // accumulate算法对于set容器的计算 79 //--------------------------------------------- 80 //声明set容器对象和迭代器 81 SET_INT set1; 82 SET_INT::iterator si; 83 84 //向set1容器中插入元素 85 set1.insert(5); 86 set1.insert(20); 87 set1.insert(10); 88 set1.insert(15); 89 set1.insert(25); 90 91 //显示set1容器的元素值和累加结果 92 cout <<"set1: "<<endl; 93 for (si=set1.begin();si !=set1.end();++si) 94 cout<<(*si)<<" "; 95 cout<<endl; 96 cout<<"accumulate(set1.begin(),set1.end(),0)="; 97 cout<<accumulate(set1.begin(),set1.end(),0)<<endl; 98 cout<<"accumulate(set1.begin(),set1.end(),100)="; 99 cout<<accumulate(set1.begin(),set1.end(),100)<<endl; 100 return 0; 101 } 102 }