Computer >> Máy Tính >  >> Lập trình >> C ++

Cách dễ nhất để khởi tạo vectơ std ::với các phần tử được mã hóa cứng trong C ++ là gì?

Trong C ++ hiện đại [11,14,…] một vectơ được khởi tạo theo cách sau

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

Thuật toán

Begin
   Initialize the vector v.
   Using accumulate, sum up all the elements of the vector v is done.
   Print the result.
End.

Dưới đây là một ví dụ đơn giản về tính tổng các phần tử của một vectơ:

Ví dụ

#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);
}

Đầu ra

Sum of all the elements are:
25