Game Development Reference
In-Depth Information
Listing 17-2. Creating a
stack
and Adding Values
MyStack myStack;
myStack.emplace(0);
myStack.push(1);
myStack.push(2);
The
stack
provides a
push
method to push values onto the top of the
stack
. Once again you can see
that this container also has the more optimal
emplace
method, which provides a faster way to place
elements onto the top.
Now that you have values in a
stack
, you cannot access the data using array operators or iterators,
as that would break the last in, first out behavior the
stack
provides. Instead the
stack
provides the
top method, which you can see in use in Listing 17-3.
Listing 17-3. Using
stack::top
cout << "Top of the stack: " << myStack.top() << endl;
The code in Listing 17-3 would print the number 2. When you decide that you no longer need the
value on the top of the stack, you use the
pop
method to remove the top element from the
stack
.
This is shown in Listing 17-4.
Listing 17-4. Using
stack::pop
myStack.pop();
cout << "Top of the stack: " << myStack.top() << endl;
The
cout
call in Listing 17-4 would print the number 2 to your console. You can
push
and
pop
values
to and from a
stack
as often as you deem necessary. The last remaining important call on a
stack
is the empty method. A call to
myStack.empty()
would return a
bool
that when true means that your
stack
contains no values.
That's all there is to know about the
stack
container. The
queue
container is very similar but provides
first in, first out access to its elements.
The STL
queue
Container
Whereas the
stack
provides last in, first out access, the
queue
container provides first in, first out
access. You can visualize this as being like a conveyor belt. The first item you place onto the belt will
be the first item to reach the end of the belt and each subsequent added item will arrive in that order.
Listing 17-5 shows all of the code you need to use a
queue
container.