🎉welcome🎉
✒️博主介绍:一名大一的智能制造专业学生,在学习C/C++的路上会越走越远,后面不定期更新有关C/C++语法,数据结构,算法,Linux,ue5使用,制作游戏的心得,和大家一起共同成长。
✈️C++专栏:C++爬塔日记
😘博客制作不易,👍点赞+⭐收藏+➕关注
前情回顾
在上一块石碑中,我学会了怎么使用常用的替换算法,同时下一块石碑也显露出来…
- 🚄上章地址:第九章(14):STL之常用拷贝和替换算法
常用算术生成算法
- 在STL的算法最开始的时候讲过,对于大部分的算法是在头文件:algorithm当中,但是还有少部分算法在别的头文件当中,常用的算术生成就在另一个头文件当中,这个头文件是:
- numeric
常用的算术生成算法有两种:
accumulate //计算容器内元素累计总和;
fill //像容器中添加元素
accumulate
- accumulate,他可以返回容器内的元素累计的总和,返回的值类型是int,需要给它一个初始值,它是从这个初始值开始加的,如果不需要初始值,就给0
accumulate(beg,end,value);
- beg是统计区间的开始迭代器,end是结束迭代器,value就是初始值
使用:
#include<iostream>
using namespace std;
#include<numeric>
#include<vector>
void test1()
{
vector<int> a;
int add = 0;
for (int i = 0; i < 10; i++)
{
a.push_back(i);
add += i;
}
cout << add << endl;
cout << accumulate(a.begin(), a.end(), 0) << endl;
cout << accumulate(a.begin(), a.end(), 5) << endl;
}
int main()
{
test1();
return 0;
}
fill
- fill可以向容器填充指定的元素
fill(beg,end,value);
- beg是填充区间的开始迭代器,end是结束迭代器,value就是填充值
使用:
#include<iostream>
using namespace std;
#include<numeric>
#include<vector>
void print(vector<int> &a)
{
for (auto b = a.begin();b < a.end(); b++)
{
cout << *b << " ";
}
cout << endl;
}
void test1()
{
vector<int> a;
a.resize(10);
print(a);
fill(a.begin(), a.end(), 10);
print(a);
}
int main()
{
test1();
return 0;
}
下一座石碑
- 这座石碑倒下了,露出了下一座石碑…
😘预知后事如何,关注新专栏,和我一起征服C++这座巨塔
🚀专栏:C++爬塔日记
🙉都看到这里了,留下你们的👍点赞+⭐收藏+📋评论吧🙉