How to get the first element from the top of a stack in C++

1 Answer

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

using namespace std; 

void printStack(stack<int> st) {
  while (!st.empty()) {
     cout << st.top() << ' ';
     st.pop();
  }
}

int main ()
{
    stack<int> st;
    int array[5] = {1, 7, 3, 5, 4};

    for (int i = 0; i < 5; i++) 
        st.push(array[i]);
        
    printStack(st);
    
    cout << endl;

    cout << st.top();
    
    return 0;
} 
   
   
   
/*
run:
   
4 5 3 7 1 
4

*/

 



answered Apr 6, 2020 by avibootz
...