C++ Development of Generic Programming Lecture 6 [stack container]

1. Basic concepts

The stack container is the stack learned in our data structure.

Characteristics of such a container is: after FILO (First In Last Out, FILO) , which has only one outlet.

Only the top element in the stack can be used by the outside world, so the stack does not allow traversal behavior

Data entering the stack is called-  stacking push

Popping data from the stack is called-popping  pop

2. Commonly used interfaces

Function description: Commonly used external interface of stack container

Constructor:

  • stack<T> stk; //stack is implemented using template classes, the default structure of the 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 elements to the top of the stack
  • pop(); //Remove the first element from the top of the stack
  • top(); //Return to the top element of the stack

Size operation:

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

Example:

#include <stack>

//栈容器常用接口
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();

	system("pause");

	return 0;
}

to sum up:

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

Guess you like

Origin blog.csdn.net/Kukeoo/article/details/114049958