您的位置:首页 > 其它

STL之stack容器

2017-05-16 14:47 190 查看
1 .stack是一种先进后出(First In Last Out,FILO)的数据结构,它只有一个出口。stack容器允许新增元素,移除元素,取得栈顶元素,但是除了最顶端外,没有任何其他方法可以存取stack的其他元素。换言之,stack不允许有遍历行为。

有元素推入栈的操作称为(入栈、进栈、压栈):push,将元素推出stack的操作称为(出栈、弹栈)pop.

如图:



2 .stack所有元素的进出都必须符合”先进后出”的条件,只有stack顶端的元素,才有机会被外界取用。Stack不提供遍历功能,也不提供迭代器。

3.stack容器的常用操作

--------------------------------------------
--------------------------------------------
------------ stack()的构造函数 ---------------

//stack采用模板类实现, stack对象的默认构造形式:
stack<T> stkT;
//拷贝构造函数
stack(const stack &stk);

--------------------------------------------
--------------------------------------------
------------ stack()的赋值操作 --------------

//重载等号操作符
stack& operator=(const stack &stk);

--------------------------------------------
--------------------------------------------
---------- stack()的数据存取操作 -------------

push(elem);     //向栈顶添加元素
pop();          //从栈顶移除第一个元素
top();          //返回栈顶元素

--------------------------------------------
--------------------------------------------
------------- stack()的大小操作 -------------
empty();        //判断堆栈是否为空
size();         //返回堆栈的大小

示例:
//stack容器存放简单的数据类型

#include <stdlib.h>
#include <stack>
#include <iostream>
using namespace std;

void test00()
{
stack<int> s;
stack<int> s1;
s.push(1);
s.push(2);
s.push(3);
s1 = s; //栈的赋值操作
cout<<"栈s的大小是: "<<s.size()<<endl;   //获得栈的大小操作
cout<<"栈s1的大小是: "<<s1.size()<<endl; //获得栈的大小操作
while (!s.empty())  //判断栈是否为空
{
int val = s.top();
cout<<val<<endl; //获得栈顶的元素
s.pop(); //弹出栈元素
}
}
int main()
{
test00();
system("pause");
return 0;
}

结果:
栈s的大小是:  3
栈s1的大小是: 3
3
2
1

示例:
//stack容器存放复杂的数据类型
#include <stdlib.h>
#include <stack>
#include <string>
#include <iostream>
using namespace std;

class Student
{
public:
Student(string name,int age)
{
this->mname = name;
this->mage = age;
}
Student(){}
~Student(){}
public:
string mname;
int mage;
};
void test01()
{
stack<Student> s;
s.push(Student("hello",22));
s.push(Student("world",23));
s.push(Student("welcome",24));
s.push(Student("you",25));
while (s.size()>0)
{
Student &val = s.top();
cout<<val.mname<<" "<<val.mage<<endl;
s.pop();
}
}

int main()
{
test01();
system("pause");
return 0;
}

打印结果:
you     25
welcome 24
world   23
hello   22

示例:
//stack容器存放复杂的数据类型指针
#include <stdlib.h>
#include <stack>
#include <string>
#include <iostream>
using namespace std;

class Student
{
public:
Student(string name,int age)
{
this->mname = name;
this->mage = age;
}
Student(){}
~Student(){}
public:
string mname;
int mage;
};
void test01()
{
stack<Student*> s;
s.push(new Student("hello",22));
s.push(new Student("world",23));
s.push(new Student("welcome",24));
s.push(new Student("you",25));
while (s.size()>0)
{
Student *val = s.top();
cout<<val->mname<<" "<<val->mage<<endl;
s.pop();
if (val != NULL)
{
delete val;
val = NULL;
}
}
}

int main()
{
test01();
system("pause");
return 0;
}

结果:
you     25
welcome 24
world   23
hello   22
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: