Initialize std::vector with Hardcoded Elements in C++



In modern C++ [11,14,…] a vector is initialized in the following way

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

Algorithm

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

Here is a simple example of sum up the elements of a vector:

Example

 Live Demo

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

Output

Sum of all the elements are:
25
Updated on: 2019-07-30T22:30:25+05:30

613 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements