这个 数字标题 这是问题的一部分 数字图书馆 在C++ STL中。该库包含基本的数学函数和类型,以及优化的数值数组和对随机数生成的支持。数字标题中的一些函数:
null
- 极少量
- 积累
- 减少
- 内积
- 部分和等。
本文解释 积累 和 部分和 在数字标题中,可在竞争性编程期间使用,以节省时间和精力。
1) 累加(): 此函数返回介于 [第一,最后) 用可变和。我们通常使用线性运算求出特定范围或完整数组中的元素之和,这需要将该范围内的所有元素逐个相加,并在每次迭代后将其存储到某个变量中。
语法:
accumulate(first, last, sum);
或
accumulate(first, last, sum, myfun);
参数:
- 首先,最后: 要添加元素的范围的第一个和最后一个元素
- 总数: 总和的初始值
- 我的乐趣: 执行任何特定任务的功能。
例如,我们可以找到元素在第一个和最后一个之间的乘积。
CPP
// C++ program to demonstrate working of accumulate() #include <iostream> #include <numeric> using namespace std; // User defined function int myfun( int x, int y) { // for this example we have taken product // of adjacent numbers return x * y; } int main() { // Initialize sum = 1 int sum = 1; int a[] = { 5, 10, 15 }; // Simple default accumulate function cout << "Result using accumulate: " ; cout << accumulate(a, a + 3, sum); // Using accumulate function with // defined function cout << "Result using accumulate with" "user-defined function: " ; cout << accumulate(a, a + 3, sum, myfun); // Using accumulate function with // pre-defined function cout << "Result using accumulate with " "pre-defined function: " ; cout << accumulate(a, a + 3, sum, std::minus< int >()); return 0; } |
输出
Result using accumulate: 31Result using accumulate withuser-defined function: 750Result using accumulate with pre-defined function: -29
有关更多参考信息,请参见此示例问题: 第1个和第2个最小元素之间的所有元素之和
2) 部分和(): 此函数将数组中相应元素的部分和分配给第二个数组的每个位置。它返回介于 [第一,最后) 并将其存储在另一个数组b中。
例如,如果x代表[第一,最后]中的一个元素,y代表结果中的一个元素,则ys可以计算为:
y0 = x0 y1 = x0 + x1 y2 = x0 + x1 + x2 y3 = x0 + x1 + x2 + x3 y4 = x0 + x1 + x2 + x3 + x4
语法:
partial_sum(first, last, b);
或
partial_sum(first, last, b, myfun);
参数:
- 首先,最后: 要添加元素的范围的第一个和最后一个元素
- b: 存储相应部分和的数组索引
- 我的乐趣: 用于执行任何特定任务的用户定义函数
CPP
// C++ program to demonstrate working of partial_sum() #include <iostream> #include <numeric> using namespace std; // user defined function int myfun( int x, int y) { // the sum of element is twice of its // adjacent element return x + 2 * y; } int main() { int a[] = { 1, 2, 3, 4, 5 }; int b[5]; // Default function partial_sum(a, a + 5, b); cout << "Partial Sum - Using Default function: " ; for ( int i = 0; i < 5; i++) cout << b[i] << ' ' ; cout << '' ; // Using user defined function partial_sum(a, a + 5, b, myfun); cout << "Partial sum - Using user defined function: " ; for ( int i = 0; i < 5; i++) cout << b[i] << ' ' ; cout << '' ; return 0; } |
输出
Partial Sum - Using Default function: 1 3 6 10 15 Partial sum - Using user defined function: 1 5 11 19 29
本文由 阿比纳夫·蒂瓦里 .如果你喜欢GeekSforgek,并想贡献自己的力量,你也可以使用 写极客。组织 或者把你的文章寄去评论-team@geeksforgeeks.org.看到你的文章出现在Geeksforgeks主页上,并帮助其他极客。如果您发现任何不正确的地方,或者您想分享有关上述主题的更多信息,请写下评论。
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END