0

Efficient way of getting sum of stack elements, without emptying it or copying it to other stack? What I am doing is:

    stack<int> si;
    int sum = 0;
    stack<int> tsi(si);
    while (!tsi.empty()) {
        sum += tsi.top();
        tsi.pop();
    }

This can be done using https://ideone.com/i7ha2j midified verson of: https://stackoverflow.com/a/13428630/7267150

Any other way to achieve the requirement (this case, sum)?? I prefer STL (is it possible).

some user
  • 1,693
  • 2
  • 14
  • 31

2 Answers2

1

You can't iterate over stack so there isn't an easy way. You can use dequeue<int> or stack<int> to insert each top element. Then, use another loop to reinsert them back to original stack<int> si, if you have to use stack. Otherwise, try to switch to vector<int> for easy iteration.

O Dundar
  • 90
  • 1
  • 6
0

Stack isn't the right container to choose here. You should have a look at std::vector, following which you could do something of this sort :

#include <vector>

std::vector< int > vec;
int sum = 0;
for( auto const & it : vec )
{
  sum += it;
}

The main reason for choosing a std::vector over a std::stack is due to the easier capability to iterate over vectors.

Vishaal Shankar
  • 1,648
  • 14
  • 26