当前位置:网站首页>numeric学习之iota,accumulate
numeric学习之iota,accumulate
2022-07-25 23:21:00 【班公湖里洗过脚】
本篇学习记录numeric的iota,accumulate的使用方式
函数
函数 | |
iota(c++11) | 用从起始值开始连续递增的值填充一个范围 (函数模板) |
| 对一个范围内的元素求和 (函数模板) | |
| 计算两个范围的元素的内积 (函数模板) | |
| 计算范围内各相邻元素之间的差 (函数模板) | |
| 计算范围内元素的部分和 (函数模板) | |
1.iota(first, last, value) 用从起始值开始连续递增的值填充一个范围
例如vector<int> vec(10);定义10个元素,如果要给他赋一个顺序递增的值,可能需要这样
vector<int> vec{0,1,2,3,4,5,6,7,8,9};//元素太多就不好写了。
或者下面这种。
for(int i = 0; i < 10; ++i)
vec.push_back(i);
那么使用iota函数可以更方便优雅得处理这种问题
#include <iostream>
#include <vector>
#include <numeric>
using namespace std;
int main()
{
vector<int> vec(10);
iota(vec.begin(), vec.end(), 10);
for(auto n: vec)
cout << n << " ";
cout << endl;
cout << "Hello World!" << endl;
return 0;
}运行结果:

参数first, last, value - 以 value 开始,按顺序递增填充的值的范围
2.accumulate(first, last, value) 对一个范围内的元素求和
| first, last | - | 要求和的元素范围 |
| init | - | 和的初值 |
代码示例:
#include <iostream>
#include <vector>
#include <numeric>
using namespace std;
int main()
{
vector<int> vec(10);
iota(vec.begin(), vec.end(), 10);
int sum = accumulate(vec.begin(), vec.end(), 0);
int sum2 = accumulate(vec.begin(), vec.end(), 100);
cout << "sum========" << sum << endl;
cout << "sum2=======" << sum2 << endl;
cout << "Hello World!" << endl;
return 0;
}
sum2比sum多100,是因为sum2求和时给初始值为100.
参考:
标准库头文件 <numeric> - cppreference.com
边栏推荐
- Cuteone: a onedrive multi network disk mounting program / with member / synchronization and other functions
- Servlet overview
- 推荐系统——An Embedding Learning Framework for Numerical Features in CTR Prediction
- Strategy mode_
- PHP JSON variable array problem
- 1913. 两个数对之间的最大乘积差-无需排序法
- 类和对象(3)
- The VM session was closed before any attempt to power it on
- Drive board network cable directly connected to computer shared network configuration
- Classes and objects (3)
猜你喜欢
随机推荐
Explain in detail the addition (+) operation in JS, basic data type addition, reference data type addition, and the underlying operation rules, [] + {}, {} + []
Qt风格(QSS)应用之QProgressBar
动态内存管理
ETL tool (data synchronization) II
Take away applet with main version of traffic / repair to add main access function of traffic
Firewall command simple operation
Which securities firm is the best and safest for beginners to open an account
Custom MVC principle
PyTorch的数据输入格式要求及转换
Enterprise level inventory management system of code audit
JS get the current date and time
电商RPA,大促轻松上阵的法宝
PHP wechat scan code, follow official account and authorize login source code
Serialize addition, deletion, modification and query
Unity uses macros
Redis expiration key deletion strategy [easy to understand]
VisualBox启动虚拟机报错:The VM session was closed before any attempt to power it on.
How to set pseudo static for WordPress fixed links
File contains vulnerability
CTS test method "suggestions collection"









