In C++, we can quickly find array sum using accumulate()
Time Complexity: O(n)
Space Complexity: O(n) where n is the size of the array.
Sum of vector:
CPP
#include <iostream>
#include <vector>
#include <numeric>
using namespace std;
int arraySum(vector< int > &v)
{
int initial_sum = 0;
return accumulate(v.begin(), v.end(), initial_sum);
}
int main()
{
vector< int > v{5 , 10 , 15} ;
cout << arraySum(v);
return 0;
}
|
Time Complexity: O(n)
Space Complexity: O(n) where n is the size of the array.
We can also use a custom function in accumulate. Refer numeric header in C++ STL | Set 1 (accumulate() and partial_sum()) for details.
Last Updated :
01 Feb, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...