DebareDaDauntless
DebareDaDauntless

Reputation: 521

Stacks and their implementation

I am confused in how stacks work, if you have a stack like

stack<string,vector<int>>

I understand the container is a container of the type of vector, which contains intergers, but then what is the purpose of the string? Or even if its not string, maybe its a bool. What purpose does the first argument serve?

#include <iostream>       
#include <stack>         
#include <vector>         
#include <string>
using namespace std;

int main ()
{
   stack<string,vector<int> > third;  
    third.emplace(1);


  cout << "size of third: " << third.size() << '\n';

}

Upvotes: 1

Views: 111

Answers (2)

Tony Delroy
Tony Delroy

Reputation: 106096

Your...

stack<string,vector<int>>

...is not the right way to use the std::stack template. Almost always you simply need one template parameter, which is the value type for elements in the stack, so stack<string> would be relatively common, and stack<vector<int>> is entirely plausible but less often seen.

The second parameter is there so you can specify an alternative container over which the stack API should be layered, and not something you normally need to vary as the default of std::deque<T>, where T is the first template parameter to stack, is generally just fine.

If you did need to specify a second template parameter, it would usually be some_container<T>, rather than the legal-but-misleading mismatch of string for T and vector<int> postulated in your question. Confusingly, the actual type of the first template parameter to stack is only used to specify the default of std::deque<T> for the second parameter - the container type. The stack's actual element type is taken from the container type, so when you explicitly specify a container type then the first template parameter to stack<> is just a place-holder and is functionally ignored. This is unfortunate - I'd argue that the Standard requiring a static assertion that the first parameter matches the container's element_type would be useful protection against misleading code.

There are limitations on the container type too - it needs to support certain functions and provide certain types/typedefs for stack to use it for the actual data storage.

Upvotes: 3

john
john

Reputation: 87959

stack<string,vector<int>> makes no sense, it's a stack of strings which is stored in a vector of ints. Obviously that doesn't work.

stack<int> is a stack of ints which is stored in a deque<int> (the default).

stack<int,vector<int>> is a stack of ints which is stored in a vector of ints.

stack<int,MyCustomStorage> is a stack of ints which is stored in a custom class (which obviously you have to write yourself).

Edit

It appears that in the template stack<T,C> T is only used to provide a default for C, it defaults to deque<T>. The type of the elements in the stack is always C::value_type.

Upvotes: 2

Related Questions