C++高级_Stack容器_STL标准模板库
Stack容器是什么?
stack是堆栈容器,是一种“先进后出”的容器。
stack是简单地装饰deque容器而成为另外的一种容器。
使用的时候需要添加头文件: #include
Stack(堆栈) 是一个容器类的改编,为程序员提供了堆栈的全部功能,— 也就是说实现了一个先进后出(FILO)的数据结构
Stack的默认构造:
stack<T> zploo; //stack采用模板类实现,stack对象的默认构造形式
stack<int> zploo; //一个存放int的stack容器
stack<float> zploo; //一个存放float的stack容器
stack<string> zploo; //一个存放string的stack容器
/*尖括号内可以设置指针类型 或 自定义类型*/
stack的拷贝构造和赋值:
stack(const stack &zploo); //拷贝构造函数
stack& operator= (const stack &zploo); //重载等号操作符
stack的push() 与 pop() 方法:
stack.push(elem); //往栈头添加元素
stack.pop(); //从栈头移除第一个元素
stack的数据存取:
stack.top(); //返回最后一个压入栈元素
stack的大小:
stack.empty(); //判断堆栈是否为空
stack.size(); //返回堆栈的大小
联系演示代码:
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <deque>
using namespace std;
void printDequeInt(deque<int> &zploo)
{
for (deque<int>::iterator it = zploo.begin(); it != zploo.end(); it++) {
cout << *it << " ";
}
cout << endl;
}
void testDeque()
{
deque<int> d;
d.push_back(1);
d.push_back(3);
d.push_back(4);
d.push_back(5);
d.push_back(7);
printDequeInt(d);
d.push_front(-1);
d.push_front(-2);
d.push_front(-3);
d.push_front(-4);
d.push_front(-6);
printDequeInt(d);
d.front() = -100;
d.back() = 1000;
printDequeInt(d);
}
//1, 4,5,7,8,9,8,3,8,10,8
void testDeuqe2()
{
int array[11] = { 1, 4, 5, 7, 8, 9, 8, 3, 8, 10, 8 };
deque<int> d(array, array+10);
for (deque<int>::iterator it = d.begin(); it != d.end();) {
if (*it == 8) {
it = d.erase(it);
}
else {
it++;
}
}
printDequeInt(d);
}
int main(void)
{
//testDeque();
testDeuqe2();
return 0;
}
最后修改于 2015-10-30