การสรุปองค์ประกอบทั้งหมดของเวกเตอร์ C++ ทำได้ง่ายมากโดยใช้วิธี std::accumulate ถูกกำหนดในส่วนหัว <ตัวเลข> มันสะสมค่าทั้งหมดที่ระบุในเวกเตอร์ไปยังผลรวมที่ระบุ
อัลกอริทึม
Begin Declare v of vector type. Initialize some values into v vector in array pattern. Print “Sum of all the elements are:”. Call accumulate(v.begin(),v.end(),0) to calculate the sum of all values of v vector. Print the result of sum. End.
โค้ดตัวอย่าง
#include<iostream>
#include<vector>
#include<numeric>
using namespace std;
int main() {
vector<int> v = {2,7,6,10};
cout<<"Sum of all the elements are:"<<endl;
cout<<accumulate(v.begin(),v.end(),0);
} ผลลัพธ์
Sum of all the elements are: 25