C++ STL stack

和弘博
2023-12-01

template <class T, class Container = deque<T> > class stack;
LIFO stack
Stacks are a type of container adaptor, specifically designed to operate in a LIFO context (last-in first-out), where elements are inserted and extracted only from one end of the container.

stacks are implemented as  containers adaptors, which are classes that use an encapsulated object of a specific container class as its  underlying container, providing a specific set of member functions to access its elements. Elements are  pushed/ popped from the  "back" of the specific container, which is known as the  top of the stack.

The underlying container may be any of the standard container class templates or some other specifically designed container class. The container shall support the following operations:
  • back
  • push_back
  • pop_back

The standard container classes  vectordeque and  list fulfill these requirements. By default, if no container class is specified for a particular  stack class instantiation, the standard container  deque is used.



#include "algostuff.hpp"

#include <iterator>
#include <ostream>
#include <numeric>
#include <stack>
using namespace std;


int main(){
stack<int> st;
st.push(1);
st.push(2);
st.push(3);


cout<<st.top()<<' ';
st.pop();
cout<<st.top()<<' ';
st.pop();


st.top()=77;


st.push(4);
st.push(5);


st.pop();


while(!st.empty()){
cout<<st.top()<<' ';
st.pop();
}
cout<<endl;


return 1;

}



编译后输出:

3 2 4 77 


 类似资料: