Skip to content

Wiki

stack container

About 3 min read

1.stack container

1.1.Basic concepts of stack

Concept:A stack is alast-in, first-out(First In Last Out, FILO) data structure, it has only one exit

说明: 2015-11-15_195707

Only the element at the top of the stack can be accessed externally, so the stack does not allow traversal behavior.

Pushing data onto the stack is called --- push push

Popping data from the stack is called --- Pop pop

Stacks in everyday life:

img

img

1.2.Common stack interfaces

Function description: common external interfaces of the stack container

Constructor:

  • stack<T> stk; //stack is implemented as a template class; the default constructor form of a stack object
  • stack(const stack &stk); //copy constructor

Assignment operation:

  • stack& operator=(const stack &stk); // Overload the equal sign operator

Data Access:

  • push(elem); // Add an element to the top of the stack
  • pop(); // Remove the first element from the top of the stack
  • top(); // Return the top element of the stack

Size operations:

  • empty(); // Determine whether the stack is empty
  • size(); // Return the size of the stack

Example:

#include <iostream>
#include <stack>

using namespace std;

//栈容器常用接口
void test01()
{
	//创建栈容器 栈容器必须符合先进后出
	stack<int> s;

	//向栈中添加元素,叫做 压栈 入栈
	s.push(10);
	s.push(20);
	s.push(30);

	while (!s.empty()) {
		//输出栈顶元素
		cout << "栈顶元素为: " << s.top() << endl;
		//弹出栈顶元素
		s.pop();
	}
	cout << "栈的大小为:" << s.size() << endl;

}

int main() {

	test01();


	return 0;
}

Operation result:

栈顶元素为: 30
栈顶元素为: 20
栈顶元素为: 10
栈的大小为:0

Summary:

  • Push --- push
  • Pop --- pop
  • Return the top of the stack --- top
  • Determine whether the stack is empty --- empty
  • Return the stack size --- size