example3_different_container.cpp

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#include <iostream>
#include <stack>
#include <vector>
#include <list>

// Note 2nd typename to accept any container
template <typename T, typename Container>
void printStackInfo(const std::stack<T, Container>& s) {
    std::cout << "Stack size: " << s.size() 
              << ", Top element: " << (s.empty() ? 0 : s.top()) << std::endl;
}

int main() {
    std::stack<int> defaultStack;
    // >> allowed in C++11
    std::stack<int, std::vector<int>> vectorStack;
    std::stack<int, std::list<int>> listStack;

    for (int i = 1; i <= 5; ++i) {
        defaultStack.push(i);
        vectorStack.push(i * 10);
        listStack.push(i * 100);
    }

    std::cout << "Default stack (deque): ";
    printStackInfo(defaultStack);

    std::cout << "Vector-based stack: ";
    printStackInfo(vectorStack);

    std::cout << "List-based stack: ";
    printStackInfo(listStack);

    return 0;
}
Back to stack