C/C++教程

C++STL(四) stack、queue容器

本文主要是介绍C++STL(四) stack、queue容器,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

stack容器基本概念

stack是一种先进后出(First In Last Out,FILO)的数据结构,它只有一个出口,形式如图所示。stack容器允许新增元素,移除元素,取得栈顶元素,但是除了最顶端外,没有任何其他方法可以存取stack的其他元素。换言之,stack不允许有遍历行为。

有元素推入栈的操作称为:push,将元素推出stack的操作称为pop.

ueue容器基本概念

Queue是一种先进先出(First In First Out,FIFO)的数据结构,它有两个出口,queue容器允许从一端新增元素,从另一端移除元素。

 

#include<iostream>
#include<stack>
#include<queue>
using namespace std;

//push
//pop
//top
//empty
//size

void test01() {
	stack<int> s1;
	s1.push(1);
	s1.push(2);
	s1.push(3);
	s1.push(4);

	cout << s1.size() << endl;
	for (int i = 0;!s1.empty(); i++) {
		cout << s1.top() << endl;
		s1.pop();
	}
}

//push
//pop
//front
//back
//empty
//size

void test02() {
	queue<int> q1;
	q1.push(1);
	q1.push(2);
	q1.push(3);
	q1.push(4);

	cout << q1.back() << endl;

	for (int i = 0; q1.size()!=0; ++i) {
		cout << i << ".front=" << q1.front() << endl;
		q1.pop();
	}
}

int main() {
	test01();
	cout << "---------------" << endl;
	test02();
	system("pause");
	return EXIT_SUCCESS;
}

 

这篇关于C++STL(四) stack、queue容器的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!