Hello

Can you tell me why my for loop below doesn't show all the elements contained in a stack (stacks size = 3).

It only shows the top 2 elements when it shoudl show all 3?

Also another question, is there a way to show the contents of a stack without deleting the top element(or any elements).

Ie, If I have a stack with a size of 10, how do I output/refer to the 3rd element of that stack? I cant use stack.at(3) or stack.top(3)?

#include <iostream>
#include <stack>

using namespace std;

int main() {
    
    stack <int> list;
    
    list.push(20);
    list.push(10);
    list.push(2323);
    
    cout << list.size() << endl;
    
    for (int i=0; i<list.size(); i++) {      // should display all elements in stack right? but only displays the 1st 2??
        cout << "List " << i << "= " << list.top() << endl;
        list.pop();
    }
    
    /*     This works , ie , displays all elements of the stack
    for (int i=list.size(); i>0; i--) {
        cout << "List " << i << "= " << list.top() << endl;
        list.pop();
    }
    */
    
    system("PAUSE");
    return 0;
}

Recommended Answers

All 2 Replies

Put,

cout << list.top() << endl;

after the for loop.

Its because of logic :

for (int i=0; i<list.size(); i++) { ...}

Lets make a table :

i   list.size()   list.top   i < list.size()
----------------------------------------------
0     3          2323            true
1     2          10                true
1     1          20                false

So what a for loop does is this :

for(  statement1;  bool statement ; increment statement; )  { loop body}

First statement1 gets executed
Then bool statement gets executed
Then loop body gets executed
Then increment statement gets executed

Following this that the last element in the table does
not get executed.

I am not sure why you are using list anyways. Use vector.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.