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

วิธีง่ายที่สุดในการเริ่มต้น std::vector ด้วยค่าคงที่ใน C++

ใน C++ สมัยใหม่ [11,14,...] Vector เริ่มต้นได้ดังนี้:

std::vector<int> vec = {1,2,3};

อัลกอริทึม

Begin
    Initialize vector v
    Use accumulate to sum all elements
    Print result
End.

ตัวอย่าง: ผลรวมสมาชิก Vector

#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