如何使用 C++ 中的 STL 查找向量中元素的和?
在本教程中,我们将讨论一个程序,了解如何使用 C++ 中的 STL 查找向量中元素的和。
要查找给定向量的元素之和,我们将使用 STL 库中的 accumulate() 方法。
示例
#include <bits/stdc++.h>
using namespace std;
int main(){
//defining the vector
vector<int> a = { 1, 45, 54, 71, 76, 12 };
cout << "Vector: ";
for (int i = 0; i < a.size(); i++)
cout << a[i] << " ";
cout << endl;
//calculating sum of the elements
cout << "Sum = "<< accumulate(a.begin(), a.end(), 0);
return 0;
}输出
Vector: 1 45 54 71 76 12 Sum = 259
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C #
MongoDB
MySQL
JavaScript
PHP