stack和queue(一)

接下来讲解一些stack栈和queue的简单使用

stack的概念

stack是一种容器适配器,专门用在具有后进先出操作的上下文环境中,其删除只能从容器的一端进行 元素的插入与提取操作。  特性是先进后出  后进先出

构造一个栈堆   

int main()
{
	deque<int> mydeque(3, 100);          // deque with 3 elements
	vector<int> myvector(2, 200);        // vector with 2 elements

	stack<int> first;                    // 构造空栈
	stack<int> second(mydeque);         // 拷贝deque内容

	stack<int, vector<int> > third;  // 使用vector容器的空栈
	stack<int, vector<int> > fourth(myvector);//使用拷贝vector容器的栈

	cout << "size of first: " << first.size() << '\n';
	cout << "size of second: " << second.size() << '\n';
	cout << "size of third: " << third.size() << '\n';
	cout << "size of fourth: " << fourth.size() << '\n';

	r

empty是stack的成员函数 用于检测当前stack是否为空  返回布尔值 若为空返回真  不为空返回假

这里的empty常常用与出栈遍历时作为while循环结束的条件来使用

返回stack中元素的个数

	cout << "size of first: " << first.size() << '\n';
	cout << "size of second: " << second.size() << '\n';
	cout << "size of third: " << third.size() << '\n';
	cout << "size of fourth: " << fourth.size() << '\n';

返回栈顶元素的引用

将stack中尾部的元素弹出

top和pop常常在遍历栈时配合完成出栈和打印操作

将元素val压入stack中

接下来建立一个栈并且完成栈的遍历

int main()
{
	stack<int> s;
	s.push(1);
	s.push(10);
	s.push(12);
	s.push(14);
	s.push(15);
	s.push(16);
	s.push(18);
	s.push(19);
	while (!s.empty())
	{
		int a = s.top();
		cout << a << " ";
		s.pop();
	}
	cout << endl;
	return  0;
}

接下来讲解一下queue队列的简单使用

队列是一种容器适配器,专门用于在FIFO上下文(先进先出)中操作,其中从容器一端插入元素,另一端 提取元素。  队列的特性是先进先出

构造容器适配器对象

测试用例

int main()
{
	deque<int> mydeck(3, 100);        
	list<int> mylist(2, 200);        

	queue<int> first;                 //创建一个空队列
	queue<int> second(mydeck);       //拷贝mydeck容器内容

	queue<int,list<int> > third; //创建一个使用list容器的空队列
	queue<int, list<int> > fourth(mylist);//创建一个使用list容器的队列并且将mylist的内容拷贝使用

	cout << "size of first: " << first.size() << endl;
	cout << "size of second: " << second.size() << endl;
	cout << "size of third: " << third.size() << endl;
	cout << "size of fourth: " << fourth.size() << endl;

	return 0;
}

检测队列是否为空,是返回true,否则返回false

返回队列中有效元素的个数

返回队头元素的引用

返回队尾元素的引用

在队尾将元素val入队列

将队头元素出队列

接下来创建一个简单的队列并对其进行遍历

int main()
{
	queue<int> q;
	q.push(1);
	q.push(21);
	q.push(31);
	q.push(41);
	q.push(51);
	q.push(61);
	q.push(71);

	while (!q.empty())
	{
		int a = q.front();
		cout << a << " ";
		q.pop();

	}
	cout << endl;
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值