How to Find the Sum of All Elements in a List in C++ STL?
In C++, a list is a sequence container provided by the STL library that represents a doubly linked list and allows to store data in non-contiguous memory locations. In this article, we will learn how to find the sum of all elements in a list in C++.
Example:
Input:
myList = {10, 20, 30, 40, 50};
Output:
The sum of all elements in the list is: 150
Sum of All Elements in a List in C++
To find the sum of all elements in a std::list in C++, we can use the std::accumulate() function provided by the <numeric> header that finds the sum of all the elements in the given range with the variable sum.
Syntax to Find the Sum of All Elements in a List
accumulate(first, last, sum);
Here,
- first and last are iterators pointing to beginning and one position past the end of list respectively.
- sum is initial value of the sum (0 here)
C++ Program to Find the Sum of All Elements in a List
The following program demonstrates how we can use the std::accumulate function to find the sum of all elements in a list in C++.
// C++ program to find the sum of all elements in a list
#include <iostream>
#include <list>
#include <numeric>
using namespace std;
int main()
{
// Initializing a list of integers
list<int> myList = { 10, 20, 30, 40, 50 };
// Finding the sum of all elements
int result
= accumulate(myList.begin(), myList.end(),
0); // initial value of sum is 0 here
// Printing the sum of all elements in the list
cout << "The sum of all elements in the list is : "
<< result;
return 0;
}
Output
The sum of all elements in the list is : 150
Time Complexity: O(N), where N is the size of the list.
Auxiliary Space: O(1)
Contact Us