Stacks in C++

· by

Contents

Minimum Example

#include <iostream>
#include <stack>

using namespace std;



int main(){
    stack<int> myStack;

    myStack.push(5);
    cout << "Size of stack: " << myStack.size() << endl;

    myStack.push(4);

    // get the element on the top
    cout << "Top: " << myStack.top() << endl;

    // it does NOT automatically pop!
    cout << "Top: " << myStack.top() << endl;

    // pop has NO return value!
    myStack.pop();

    cout << "Top: " << myStack.top() << endl;

    return 0;
}

Maximum number of elements

#include <iostream>
#include <stack>

using namespace std;

int main() {
    stack<int> s;
    for (unsigned int i=0; i < 1000000; i++) {
        for (unsigned int j=0; j < 100; j++) {
            s.push(i);
        }
    }

    cout << "Size of stack: " << s.size() << endl;
}
Size of stack: 100000000

100,000,000 could be added without any problems.

See also