#include stack使用方法简介

发布于 2018-11-14  476 次阅读


栈的定义
栈被实现为容器适配器,它是使用特定容器类的封装对象作为其基础容器的类,提供了一组特定的成员函数来访问其元素。 元素从特定容器的“后面”被推入/弹出,这被称为堆栈的顶部。

成员函数
Member functions
(constructor)
Construct stack (public member function )
empty
Test whether container is empty (public member function )
size
Return size (public member function )
top
Access next element (public member function )
push
Insert element (public member function )
emplace
Construct and insert element (public member function )
pop
Remove top element (public member function )
swap
Swap contents (public member function )

Non-member function overloads
relational operators
Relational operators for stack (function )
swap (stack)
Exchange contents of stacks (public member function )

Non-member class specializations
uses_allocator<stack>
Uses allocator for stack (class template )

- 演示程序

#include<iostream>
#include<stack>
#include<string>
using namespace std;

int main()
{


    //top用法
    stack<int> mystack;
    mystack.push(10);
    mystack.push(20);
    mystack.top() -= 5;
    cout << "mystack.top() is now " << mystack.top() << '\n';

    //size用法
    stack<int> myints;
    cout << "0. size: " << myints.size() << '\n';
    for (int i = 0; i < 5; i++) myints.push(i);
    cout << "1. size: " << myints.size() << '\n';
    myints.pop();
    cout << "2. size: " << myints.size() << '\n';


    //push和pop用法
    stack<int> mystack1;
    //将i元素压入栈
    for (int i = 0; i < 5; ++i) mystack1.push(i);
    cout << "Popping out elements...";
    while (!mystack1.empty())
    {
        cout << ' ' << mystack1.top();//取栈顶元素
        mystack1.pop();//栈顶元素出栈
    }
    cout << '\n';

    //emplace用法
    stack<string> myqueue1;
    myqueue1.emplace("First sentence");
    myqueue1.emplace("Second sentence");
    cout << "myqueue contains:\n";
    while (!myqueue1.empty())
    {
        cout << myqueue1.top() << '\n';
        myqueue1.pop();
    }

    //swap用于交换两个队列内的元素
    stack<int> foo, bar;
    foo.push(10); foo.push(20); foo.push(30);
    bar.push(111); bar.push(222);
    foo.swap(bar);
    cout << "size of foo: " << foo.size() << '\n';
    cout << "size of bar: " << bar.size() << '\n';

    system("pause");
    return 0;
}

运行结果

mystack.top() is now 15
0. size: 0
1. size: 5
2. size: 4
Popping out elements... 4 3 2 1 0
myqueue contains:
Second sentence
First sentence
size of foo: 2
size of bar: 3
Press any key to continue . . .

 

 


像烟花也是过一生,像樱花也是一生,只要亮过和盛开不就好了么?