
- 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
How to sum up elements of a C++ vector?
Sum up of all elements of a C++ vector can be very easily done by std::accumulate method. It is defined in <numeric> header. It accumulates all the values present specified in the vector to the specified sum.
Algorithm
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.
Example Code
#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
- How to find the sum of elements of a Vector using STL in C++?
- Extract string vector elements up to a fixed number of characters in R.
- How to replace one vector elements with another vector elements in R?
- How to copy elements of ArrayList to Java Vector
- How to remove some last elements of a vector in R?
- How to create unordered triplets of a vector elements in R?
- How to append a vector in a vector in C++?
- How to convert the repeated elements of strings in a vector to unique elements in R?
- How to divide columns of a matrix by vector elements in R?
- Add elements to a Vector in Java
- How to sum elements of a column in MySQL?
- How to select top or bottom n elements of a vector in R?
- How to sort a vector in R based on manual position of elements?
- How to find all combinations of a vector elements without space in R?
- How to find the intersection of elements in a string vector in R?

Advertisements