How to find the sum of elements of a Vector using STL in C++?
Given a vector, find the sum of the elements of this vector using STL in C++.
Example:
Input: vec = {1, 45, 54, 71, 76, 12}
Output: 259
Input: vec = {1, 7, 5, 4, 6, 12}
Output: 35
Approach: Sum can be found with the help of accumulate() function provided in STL.
Syntax:
accumulate(first_index, last_index, initial value of sum);
// C++ program to find the sum // of Array using accumulate() in STL #include <bits/stdc++.h> using namespace std; int main() { // Get the vector vector<int> a = { 1, 45, 54, 71, 76, 12 }; // Print the vector cout << "Vector: "; for (int i = 0; i < a.size(); i++) cout << a[i] << " "; cout << endl; // Find the sum of the vector cout << "\nSum = " << accumulate(a.begin(), a.end(), 0); return 0; } |
chevron_right
filter_none
Output:
Vector: 1 45 54 71 76 12 Sum = 259
Recommended Posts:
- How to find common elements between two Vector using STL in C++?
- Get first and last elements from Array and Vector in CPP
- Count elements in a vector that match a target value or condition
- How to find the maximum element of a Vector using STL in C++?
- How to find the minimum and maximum element of a Vector using STL in C++?
- Find and print duplicate words in std::vector<string> using STL functions
- vector::front() and vector::back() in C++ STL
- vector::empty() and vector::size() in C++ STL
- vector :: cbegin() and vector :: cend() in C++ STL
- vector::push_back() and vector::pop_back() in C++ STL
- vector::crend() & vector::crbegin() with example
- Find set of m-elements with difference of any two elements is divisible by k
- vector::at() and vector::swap() in C++ STL
- vector::begin() and vector::end() in C++ STL
- How to find the sum of elements of an Array using STL in C++?
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



