1. 程式人生 > >#include使用方法簡介

#include使用方法簡介

  • 棧的定義 棧被實現為容器介面卡,它是使用特定容器類的封裝物件作為其基礎容器的類,提供了一組特定的成員函式來訪問其元素。 元素從特定容器的“後面”被推入/彈出,這被稱為堆疊的頂部。
  • 成員函式

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 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 . . .