stack容器

stack容器
先进后出,只有一个口
1、stack<T>  stkT;//stack采用模板类实现
satck(const stack &stk);//拷贝构造
2、stack赋值操作
stack& operator=(const stack &stk)://重载等号操作符
3、stack数据存取操作
push(elem);//向栈顶添加元素
pop();//从栈顶移除一个元素
top();//返回栈顶元素
4、stack大小操作
empty();
size();
#include<iostream>
#include<stack>
using namespace std;

void test01()
{
	stack<int> mystack;
	mystack.push(8);
	mystack.push(2);
	mystack.push(1);
	mystack.push(8);
	
	stack<int> mystack2(mystack);//拷贝构造
	if (mystack.empty())
	{
		cout << "kon" << endl;
	}
	else
	{
		cout << "no" << endl;
	}
	while (mystack.size() > 0)
	{
		int val = mystack.top();
		cout << val << " ";
		mystack.pop();
	}
	cout << endl;
}
//放对象
class Teacher{
public:
	Teacher(string name, int age) :name(name), age(age){}
	string name;
	int age;
  
};

void test02()
{
	stack<Teacher> mystack;
	Teacher t1("aaa", 10), t2("bbb", 20), t3("ccc", 30);

	mystack.push(t1);
	mystack.push(t2);
	mystack.push(t3);

	while (mystack.size() > 0)
	{
		Teacher t = mystack.top();
		cout << t.name << t.age << endl;
		mystack.pop();
	
	}

}

//放指针
void test03()
{
	stack<Teacher*> mystack;
	Teacher t1("aaa", 10), t2("bbb", 20), t3("ccc", 30);

	Teacher *p1 = &t1;
	Teacher*p2 = &t2;
	Teacher*p3 = &t3;

	mystack.push(p1);
	mystack.push(p2);
	mystack.push(p3);

	while (mystack.size() > 0)
	{
		Teacher *p = mystack.top();
		cout << p->name << p->age <<endl;
		mystack.pop();

	}
}

int main()
{
	//test01();
	//test02();
	test03();

	return EXIT_SUCCESS;
}



全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务