How to use a stack in C++

2 Answers

0 votes
#include <iostream>       
#include <stack>          

int main ()
{
  std::stack<int> st;
 
  for (int i = 0; i < 5; i++) 
        st.push(i);
 
  while (!st.empty()) {
     std::cout << st.top() << ' ';
     st.pop();
  }
} 
    
    
    
/*
run:
    
4 3 2 1 0  
    
*/

 



answered Apr 6, 2020 by avibootz
edited 3 hours ago by avibootz
0 votes
#include <iostream>
#include <stack>

void printStack(std::stack<int> st) {
    std::cout << "Stack (top → bottom): ";
    
    while (!st.empty()) {
        std::cout << st.top() << " ";
        st.pop();
    }
}


int main() {
    std::stack<int> st;

    st.push(10);   // add element
    st.push(20);
    st.push(30);
    st.push(40);
    st.push(50);

    std::cout << st.top() << std::endl;  

    st.pop();  // removes 50

    std::cout << st.top() << std::endl;  
    
    printStack(st);
}


/*
run:

50
40
Stack (top → bottom): 40 30 20 10 

*/

 



answered 3 hours ago by avibootz

Related questions

1 answer 291 views
1 answer 76 views
1 answer 70 views
1 answer 188 views
1 answer 95 views
95 views asked Feb 2, 2023 by avibootz
1 answer 248 views
...