
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
What is the easiest way to initialize a 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
#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
- Related Articles
- What is the easiest way to reverse a String in Java?
- What is the easiest way to store date in MySQL database?
- What is the easiest way to convert a List to a Set in Java?
- What is the easiest way to lose weight without exercise?
- What is the easiest way to convert int to string in C++
- What is the best way to initialize a JavaScript number?
- std::vector::resize() vs. std::vector::reserve() in C++
- What is the easiest way to transfer files from phone to PC?
- What is the best way to initialize a JavaScript Date to midnight?
- How to shuffle a std::vector in C++
- The easiest way to concatenate two arrays in PHP?
- The easiest way to insert date records in MySQL?
- How to initialize a vector in C++?
- Difference between std::vector and std::array in C++
- What is the best way to read an entire file into a std::string in C++?

Advertisements