I am a student studying basic algorithm.
I wrote a code to get the sum of all the elements by stl:stack
.
#include <bits/stdc++.h>
using namespace std;
int main(void)
{
ios::sync_with_stdio(0);
cin.tie(0);
int k; cin >> k;
stack<int> s;
int answer=0;
while (k--)
{
int n; cin >> n;
if (n == 0)
{
s.pop();
}
else
{
s.push(n);
}
}
for (int i = 0; i < s.size(); i++)
{
answer = answer + s.top();
s.pop();
}
cout << answer;
}
Input:
5 5 4 3 2 1
Output:
6
As I intended, the result should be 15 but there is an error.
But if I replace for (int i = 0; i < s.size(); i++)
with while(!s.empty())
, get normal results.
Is there a problem with i <size()
? I'd appreciate it if you could answer.