Generic Stack (C++)

From RAD Studio Code Examples
Jump to: navigation, search

Description

This example demonstrates the usage of a generic stack in C++Builder. This example uses the header <stack> from the Dinkumware Standard C++ Library (STL).

Code

#include <stack>
#include <iostream>
using namespace std;
// ---------------------------------------------------------------------------
void __fastcall TForm1::Button1Click(TObject *Sender) {
    // Create the stack
    stack<UnicodeString>stk;

    // Add elements to the stack
    stk.push("John");
    stk.push("Mary");
    stk.push("Bob");
    stk.push("Anna");
    stk.push("Erica");

    // Show the last pushed element "Erica"
    TDialogServiceSync::MessageDialog(
        "Last elemnt pushed is: " + stk.top(), TMsgDlgType::mtInformation,
        TMsgDlgButtons() << TMsgDlgBtn::mbOK, TMsgDlgBtn::mbOK, 0);

    // Pop the last pushed element
    stk.pop();

    // Show the number of elements in the stack "4"
    TDialogServiceSync::MessageDialog(
        "The stack contains: " + IntToStr((int)stk.size()) + " elements.",
        TMsgDlgType::mtInformation, TMsgDlgButtons() << TMsgDlgBtn::mbOK,
        TMsgDlgBtn::mbOK, 0);

    // Show the last pushed element "Anna"
    TDialogServiceSync::MessageDialog(
        "Last elemnt pushed is: " + stk.top(), TMsgDlgType::mtInformation,
        TMsgDlgButtons() << TMsgDlgBtn::mbOK, TMsgDlgBtn::mbOK, 0);

    // Lambda expression for clearing the stack
    // This piece of code will execute only for 64-bit C++ applications
#ifdef _WIN64
    [&]
    () {
        stack<UnicodeString>empty;
        swap(stk, empty);
    }();
#endif

    // Show the number of elements in the stack "0"

    TDialogServiceSync::MessageDialog(
        "The stack contains: " + IntToStr((int)stk.size()) +" elements.",
        TMsgDlgType::mtInformation, TMsgDlgButtons() << TMsgDlgBtn::mbOK,
        TMsgDlgBtn::mbOK, 0);
}
// ---------------------------------------------------------------------------

Uses

See Also

Personal tools
Assistance