18.5【STL常用算数生成算法accumulate、fill】

复制代码
 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 }
复制代码

 

posted @   yub4by  阅读(54)  评论(0编辑  收藏  举报
编辑推荐:
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
阅读排行:
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!
点击右上角即可分享
微信分享提示