1 #include<iostream>
2 #include<cstdlib>
3 using namespace std;
4 #include<vector>
5 #include<numeric>
6 #include<algorithm>
7
8
9 /*
10 5.5 常用算术生成算法
11
12 算术生成算法属于小型算法,使用时包含的头文件为 #include <numeric>
13
14 5.5.1 accumulate
15
16 计算区间内 容器元素累计总和
17 accumulate(iterator beg, iterator end, value);
18 // 计算容器元素累计总和
19 // beg 开始迭代器
20 // end 结束迭代器
21 // value 起始值
22
23 5.5.2 fill
24 向容器中填充指定的元素
25 fill(iterator beg, iterator end, value);
26 // 向容器中填充元素
27 // beg 开始迭代器
28 // end 结束迭代器
29 // value 填充的值
30 */
31
32
33 void test551()
34 {
35 vector<int> v;
36 for(int i=0; i<=100; i++)
37 {
38 v.push_back(i);
39 }
40
41 //0/1~100的和:5050
42 int sum = accumulate(v.begin(), v.end(), 0); //0表示起始累加值
43 cout << sum << endl;
44
45 sum = accumulate(v.begin(), v.end(), 1000); //1000+5050
46 cout << sum << endl;
47 }
48
49
50 class MyPrint
51 {
52 public:
53 void operator()(int val)
54 {
55 cout << val << " ";
56 }
57 };
58
59
60 void test552()
61 {
62 vector<int> v;
63 v.resize(10); //v中含有10个0
64
65 cout << "填充前:" << endl;
66 for_each(v.begin(), v.end(), MyPrint());
67 cout << endl;
68
69 fill(v.begin(), v.end(), 100);
70
71 cout << "填充后:" << endl;
72 for_each(v.begin(), v.end(), MyPrint());
73 cout << endl;
74 }
75
76
77 int main()
78 {
79 test551();
80 test552();
81
82 system("pause");
83 return 0;
84 }
