c++中对数组求和
初始化一个数组
cpp
/******************************************************************************
Welcome to GDB Online.
GDB online is an online compiler and debugger tool for C, C++, Python, PHP, Ruby,
C#, OCaml, VB, Perl, Swift, Prolog, Javascript, Pascal, COBOL, HTML, CSS, JS
Code, Compile, Run and Debug online from anywhere in world.
*******************************************************************************/
#include <iostream>
#include <vector>
#include <numeric>
using namespace std;
int main()
{
int n = 10;
/* 初始化方式 */
vector<int> vec_a(n, 1);
for (int x : vec_a)
{
cout << x << " ";
}
int sum = 0;
/* 0是初始值 */
sum = accumulate(vec_a.begin(), vec_a.end(), 0);
cout << "sum = " << sum;
return 0;
}
初始化方法
初始化方法一
cpp
#include <vector>
using namespace std;
int main() {
int n = 10;
vector<int> v(n, 1); // 长度 n, 全部 = 1
}
初始化方法二
cpp
vector<int> v(10);
fill(v.begin(), v.end(), 1);
求和方法
方法一
cpp
#include <vector>
#include <numeric> // 需要这个头文件
using namespace std;
vector<int> v = {1,2,3,4,5};
int sum = accumulate(v.begin(), v.end(), 0);
方法二(自己写循环)
cpp
int sum = 0;
for (int x : v) {
sum += x;
}
方法三(下标循环)
cpp
int sum = 0;
for (int i = 0; i < v.size(); ++i) {
sum += v[i];
}
相关链接
【在线编译器】
GDB online Debugger | Compiler - Code, Compile, Run, Debug online C, C++