How to Find the Sum of All Elements in a Deque in C++?
Last Updated :
26 Mar, 2024
In C++, double-ended queues are sequence containers similar to vectors but are more efficient in the case of insertion and deletion of elements at both ends. In this article, we will learn how to find the sum of all elements in a deque in C++.
Example
Input:
myDeque ={1,2,3,4,5}
Output:
Sum of all deque elements is 15.
Sum Up All Elements of a Deque in C++
To find the sum of all the elements in a std::deque in C++, we can use the std::accumulate() method which finds the sum of the elements in the given range.
Syntax
accumulate(first, last, 0);
where,
- first : Iterator pointing to the beginning of the deque.
- last : Iterator pointing to one position past the end of the deque.
- 0: Initial value for the sum.
C++ Program to Find the Sum of All Elements in a Deque
The following program illustrates how we can find the sum of all elements in a deque in C++:
C++
// C++ Program to illustrate how to find the sum of all
// elements in a deque
#include <deque>
#include <iostream>
#include <numeric>
using namespace std;
int main()
{
// Initialize the deque
deque<int> dq = { 1, 2, 3, 4, 5 };
// Print elements of the deque
cout << "Deque Elements: ";
for (int x : dq) {
cout << x << " ";
}
cout << endl;
// Use accumulate to find the sum of all elements
int sum = accumulate(dq.begin(), dq.end(), 0);
// Print the sum of ell elemetns in the deque
cout << "Sum of elements in the Deque: " << sum;
return 0;
}
OutputDeque Elements: 1 2 3 4 5
Sum of elements in the Deque: 15
Time Complexity: O(N) here N denotes the size of the deque.
Auxiliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...