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);
CPP
// 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; } |
Vector: 1 45 54 71 76 12 Sum = 259
Time Complexity: It is linear in the distance between first_index and last_index i.e if your vector contains n number of elements between two given indices , the time complexity will be O(n).
Auxiliary Space: O(1)
Another Approach: (Using the for_each() function)
The for_each() function is an STL algorithm that applies a given function to each element in a range defined by a pair of iterators.
To find the sum of all elements in a vector using the for_each() function, we can define a lambda function or a function object that adds each element to a running total.
Syntax:
for_each(InputIt first, InputIt last, UnaryFunction f);
C++
// C++ program to find the sum // of Array using for_each() function in STL #include <bits/stdc++.h> using namespace std; int main() { // Get the vector vector< int > a = { 1, 45, 54, 71, 76, 12 }; int sum = 0; // Print the vector and calculate sum cout << "Vector: " ; for_each(a.begin(), a.end(), [&]( int i) { cout << i << " " ; sum += i; }); // Print the sum of the vector cout << "\nSum = " << sum << endl; return 0; } // This code is contributed by Susobhan Akhuli |
Vector: 1 45 54 71 76 12 Sum = 259
Time Complexity: O(N), , where N is the number of elements in the range.
Auxiliary Space: O(1)
Contact Us