• 栈的定义
    栈被实现为容器适配器,它是使用特定容器类的封装对象作为其基础容器的类,提供了一组特定的成员函数来访问其元素。 元素从特定容器的“后面”被推入/弹出,这被称为堆栈的顶部。

  • 成员函数

Member functions


Non-member function overloads


Non-member class specializations

- 演示程序
#include<iostream>
#include<stack>
#include<string>
using namespace std;

int main()
{
	

	//top用法
	stack<int> mystack;
	mystack.push(10);
	mystack.push(20);
	mystack.top() -= 5;
	cout << "mystack.top() is now " << mystack.top() << '\n';

	//size用法
	stack<int> myints;
	cout << "0. size: " << myints.size() << '\n';
	for (int i = 0; i < 5; i++) myints.push(i);
	cout << "1. size: " << myints.size() << '\n';
	myints.pop();
	cout << "2. size: " << myints.size() << '\n';


	//push和pop用法
	stack<int> mystack1;
	//将i元素压入栈
	for (int i = 0; i < 5; ++i) mystack1.push(i);
	cout << "Popping out elements...";
	while (!mystack1.empty())
	{
		cout << ' ' << mystack1.top();//取栈顶元素
		mystack1.pop();//栈顶元素出栈
	}
	cout << '\n';

	//emplace用法
	stack<string> myqueue1;
	myqueue1.emplace("First sentence");
	myqueue1.emplace("Second sentence");
	cout << "myqueue contains:\n";
	while (!myqueue1.empty())
	{
		cout << myqueue1.top() << '\n';
		myqueue1.pop();
	}

	//swap用于交换两个队列内的元素
	stack<int> foo, bar;
	foo.push(10); foo.push(20); foo.push(30);
	bar.push(111); bar.push(222);
	foo.swap(bar);
	cout << "size of foo: " << foo.size() << '\n';
	cout << "size of bar: " << bar.size() << '\n';

	system("pause");
	return 0;
}
  • 运行结果
mystack.top() is now 15
0. size: 0
1. size: 5
2. size: 4
Popping out elements... 4 3 2 1 0
myqueue contains:
Second sentence
First sentence
size of foo: 2
size of bar: 3
Press any key to continue . . .

在这里插入图片描述

Logo

权威|前沿|技术|干货|国内首个API全生命周期开发者社区

更多推荐