Stack and Vector in C++

Stack is a container adaptor. This class acts as a wrapper function to sequence containers.

There are 3 container adaptors in STL. Stack, Queue and Priority Queue.

Stack requires 3 member functions in its underlying containers.

back()
push_back()
pop_back()

Following containers satisify above conditions, vector, deque and list. By default stack is deque.

This is the function signature for stack:

template<typename _Tp, typename _Sequence = deque<_Tp> >

//This can be constructed in following ways

stack<T> wrapped_as_deque;
stack<T , list<T> > wrapped_as_list;
stack<T, vector<T> wrapped_as_vector;  //ex: std::stack<int, std::vector<int>>

//print the stack object memory address and verify the implemention
while(!wrapped_as_deque.empty())
{
   printf("%u \n", &wrapped_as_deque.top();
   ss.pop();
}

Let me explain member functions in Stack Class

push - Member function in stack class, which adds the element starting from 0th index. pop - Member function in stack class, which removes the highest index element at any point of time.

Through this two function LIFO (Last in, First Out) method is possible.

There are no iterators available in stack. No index based access. No Range based access.

Take a look at the example comparing the stack and vector.

#include <iostream>
#include <stack>
#include <vector>
using namespace std;
int main(int argc, char* argv[])
{
    stack<int> ss;
    vector<int> vv;
    for (size_t i = 0; i < 5; i++)
    {
        //Basically inserting element; 

        ss.push(i); //This member function uses push_back only in stack class

        vv.push_back(i);
    }


    //Printing the contents in stack:
    while (!ss.empty())
    {
        //Print from the last
        cout<<ss.top()<<" "; // The only way the elements are accessed in stack class
        //This member function actually calls back() function to the container c

        //Start removing from the last value
        ss.pop(); 
        //This member function actually calls pop_back() function to the container c
    }
    cout<<endl;
    //Printing the contents in vector in similar fashion, ie reverse way
    while (!vv.empty())
    {
        cout<<vv.back()<<" "; //Last element
        vv.pop_back(); //Remove the last element
    }
    cout<<endl;




    return 0;
}

We can hack the stack class to even make it access based on index like this.

class custom_stack : public std::stack<int> 
{
     using std::stack<int>::c;
}

main:

custom_stack ss;
ss.push(1);
ss.push(2);
cout<<ss.c[i];

Reference: en.cppreference.com/w/cpp/container/stack