< Previous | Contents | Next >
The Standard Template Library: Hangman
So far you’ve seen how to work with sequences of values using arrays. But there are more sophisticated ways to work with collections of values. In fact, working with collections is so common that part of standard C++ is dedicated to doing just that. In this chapter, you’ll get an introduction to this important library. Specifically, you’ll learn to:
n Use vector objects to work with sequences of values
n Use vector member functions to manipulate sequence elements
n Use iterators to move through sequences
n Use library algorithms to work with groups of elements
n Plan your programs with pseudocode
Introducing the Standard Template Library Good game programmers are lazy. It’s not that they don’t want to work; it’s just that they don’t want to redo work that’s already been done—especially if it has
been done well. The STL (Standard Template Library) represents a powerful
collection of programming work that’s been done well. It provides a group of containers, algorithms, and iterators, among other things.
So what’s a container and how can it help you write games? Well, containers let you store and access collections of values of the same type. Yes, arrays let you do
115
116 Chapter 4 n The Standard Template Library: Hangman
the same thing, but the STL containers offer more flexibility and power than a simple but trusty array. The STL defines a variety of container types; each works in a different way to meet different needs.
The algorithms defined in the STL work with its containers. The algorithms are common functions that game programmers find themselves repeatedly applying to groups of values. They include algorithms for sorting, searching, copying, merging, inserting, and removing container elements. The cool thing is that the same algorithm can work its magic on many different container types.
Iterators are objects that identify elements in containers and can be manipulated to move among elements. They’re great for, well, iterating through containers. In addition, iterators are required by the STL algorithms.
All of this makes a lot more sense when you see an actual implementation of one of the container types, so that’s up next.