c++中对数组求和

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++

相关推荐
程与留5 小时前
15_国际化和本地化:tr()、ts 文件、QM 文件、多语言切换
c++·qt
程与留7 小时前
14_Qt 样式表(QSS)入门(语法、选择器、美化实战)
c++·qt
欧特克_Glodon15 小时前
OpenCV计算机视觉开发入门与实践<二十七>:图像分割概述
c++·人工智能·opencv·计算机视觉
蒸蒸yyyyzwd15 小时前
cpp 选手秋招学习笔记 day21
c++·面试·八股
Interview Aid11216 小时前
TikTok OA 四题分享|半小时内 AC,题目基本都是实现题
java·开发语言·算法·面试·职场和发展
CoderIsArt1 天前
C#中UI 线程与 Dispatcher
开发语言·ui·c#
AI情绪识别开源1 天前
检信 ALLEMOTION OS 加密打包可执行程序 — 全面测试报告版本: v1.3功能测试 / 性能测试 /
开发语言·数据结构·人工智能·功能测试
「QT(C++)开发工程师」1 天前
C++ auto 用法详解
开发语言·c++
OPEN-F1 天前
C++STL教程:容器适配器与实用工具
开发语言·c++