Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

วิธีหาผลรวมองค์ประกอบของ Vector ด้วย STL ใน C++


ในบทช่วยสอนนี้ เราจะอภิบายโปรแกรมเพื่อทำความเข้าใจวิธีหาผลรวมองค์ประกอบของ vector โดยใช้ STL ใน C++

เพื่อหาผลรวมขององค์ประกอบของ vector ที่กำหนด เราจะใช้เมธอด accumulate() จากไลบรารี STL

ตัวอย่าง

#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