I recently started learning about stacks in C++. While looking at an example, I noticed they used the following:
void showstack(stack <int> s).
I was wondering what the <>
did, and how is it different from just using int
?
I recently started learning about stacks in C++. While looking at an example, I noticed they used the following:
void showstack(stack <int> s).
I was wondering what the <>
did, and how is it different from just using int
?
What you are looking at are template parameters.
Basically, stack
is a template, declared (in a simplified manner) like this:
template <class T>
class stack { /*...*/ };
Thus, stack
is not a class, you cannot talk about a stack type. It will only become a type once the template parameter is specified; for example: stack<int>
is a stack of integers in this case.
stack
just like many other containers is templated. You need to specify the type of elements you are going to store in the container.
template<
class T, // this what you specified in your code
class Container = std::deque<T>
> class stack;
There is no stack compiled in your code until you use one with a type, like you did.
The <>
are used for templates, which tell a class what kind of data to expect. You could replace int
with string
and you would have a stack of strings that way.