Stack栈模型

stack是堆栈容器,特点是“先进的元素后出”。其他操作方式参考vector容器

#include <stack>  

  • push()//入栈
  • empty()//是否为空
  • top()//获取栈顶元素
  • pop()//弹出栈顶元素

stack对象的拷贝构造与赋值

  • stack(const stack &stk);                           //拷贝构造函数
  • stack& operator=(const stack &stk);        //重载等号操作符

数据存取

  • stack.top();   //返回最后一个压入栈元素

大小

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

出栈 入栈

//入栈 出栈(先进后出)
void Fun1()
{
	stack<int> s;
	for (int i = 0; i<10;i++)
	{
		s.push(i + 1);
	}
	cout << "栈的大小:" << s.size() << endl;


	while (!s.empty())
	{
		int temp = s.top();//获取栈顶元素
		cout << temp << " ";
		s.pop();//弹出栈顶元素
	}
}

存放类对象

class Person
{
public:
	Person(const int age,const char *name)
	{
		this->m_age = age;
		strcpy(this->m_name, name);
	}
	void PrintP()
	{
		cout << "age:" << m_age <<" "<<"name:" << m_name << endl;
	}

private:
	int		m_age;
	char	m_name[24];
};

void Fun2()
{
	Person p1(22, "zhangsan"), p2(23, "lisi"), p3(24, "wangwu");
	stack<Person> s;
	s.push(p1);
	s.push(p2);
	s.push(p3);

	while (!s.empty())
	{
		Person p = s.top();
		p.PrintP();
		s.pop();
	}
}

存放指针类

class Person
{
public:
	Person(const int age,const char *name)
	{
		this->m_age = age;
		strcpy(this->m_name, name);
	}
	void PrintP()
	{
		cout << "age:" << m_age <<" "<<"name:" << m_name << endl;
	}

private:
	int		m_age;
	char	m_name[24];
};

void Fun3()
{
	Person p1(22, "zhangsan"), p2(23, "lisi"), p3(24, "wangwu");
	stack<Person *> s;
	s.push(&p1);
	s.push(&p2);
	s.push(&p3);

	while (!s.empty())
	{
		Person *p = s.top();
		p->PrintP();
		s.pop();
	}
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章