一、简介

二、stack相关函数用法

#include <iostream>
using namespace std;
#include <stack>
void main01()               //栈模型          
{
    stack<int> s;
    for (int i = 0; i < 10; i++)
    {
        s.push(i + 1);      //入栈
    }
    cout << "栈的大小: " << s.size() << endl;
    while (!s.empty())      //出栈
    {
        int tmp = s.top();  //获取栈顶元素
        cout << tmp<<" ";
        s.pop();            //弹出栈顶元素
    }
    cout << endl;
}
class Teacher
{
public:
    int age;
    char name[32];
public:
    void printT()
    {
        cout << "age: " << age << endl;
    }
};
void main02()                 //结构体
{
    Teacher t1, t2, t3;
    t1.age = 31;
    t2.age = 32;
    t3.age = 33;
    stack<Teacher> s;
    s.push(t1);
    s.push(t2);
    s.push(t3);
    while (!s.empty())
    {
        Teacher tmp = s.top();
        tmp.printT();
        s.pop();
    }
}
void main03()            //结构体指针
{
    Teacher t1, t2, t3;
    t1.age = 31;
    t2.age = 32;
    t3.age = 33;
    stack<Teacher*> s;
    s.push(&t1);
    s.push(&t2);
    s.push(&t3);
    while (!s.empty())
    {
        Teacher *p = s.top();
        p->printT();
        s.pop();
    }
}
void main()
{
    main01();
    main02();
    main03();
    cout << endl;
    cout << "Hello" << endl;
    system("pause");
    return;
}

1、empty()

  stack<int>s;
  s.push(1);
  s.push(2);
  cout << s.empty() << endl;   //输出0

2、size()

3、top()

 stack<int>s;
 s.push(1);
 s.push(2);
 cout << s.top() << endl;    //输出2
 s.top() += 3;               //引用可以作为左值
 cout << s.top() << endl;    //输出5

4.push()和emplace()(c++11)

 struct Node
{
    Node(int x)
    x(x){}
    int x;
};
int main()
{
    stack<Node>s1;
    s1.emplace(1);
    s1.push(Node(2));
    stack<int>s2;
    s2.emplace(1);   //OK
    return 0;
}

5、pop()

stack<int>s;
s.push(1);
s.push(2);
s.push(3);
cout << s.top() << endl;   //3
s.pop();
cout << s.top() << endl;   //2
stack<int>s;
//s.erase(); //error
//s.clear(); //error
s.push(1);
s.push(2);
s.push(3);
cout << s.size() << endl;   //3
while(!s.empty())
    s.pop();
cout << s.size() << endl;    //0

6、swap()

// stack::swap
#include <iostream>
using namespace std;
#include <stack>
int main ()
{
  std::stack<int> foo,bar;
  foo.push (10); foo.push(20); foo.push(30);
  bar.push (111); bar.push(222);
  foo.swap(bar);
  std::cout << "size of foo: " << foo.size() << '\n';
  std::cout << "size of bar: " << bar.size() << '\n';
  return 0;
}

7、运算符重载

02-01 10:21