Templates 693
19
The Standard Template Library ..........................................................................
As it is said, there is no point in reinventing the wheel. The same is true in creating pro-
grams with C++. This is why the Standard Template Library (STL) became popular. As
with other components of the Standard C++ Library, the STL is portable between various
operating systems.
All the major compiler vendors now offer the STL as part of their compilers. The STL is
a library of template-based container classes, including vectors, lists, queues, and stacks.
The STL also includes a number of common algorithms, including sorting and searching.
The goal of the STL is to give you an alternative to reinventing the wheel for these com-
mon requirements. The STL is tested and debugged, offers high performance, and is free.
Most important, the STL is reusable; after you understand how to use an STL container,
you can use it in all your programs without reinventing it.
Using Containers ............................................................................................
A containeris an object that holds other objects. The Standard C++ Library provides a
series of container classes that are powerful tools that help C++ developers handle com-
mon programming tasks.
Two types of Standard Template Library container classes are sequence and associative.
Sequencecontainers are designed to provide sequential and random access to their mem-
bers, or elements. Associativecontainers are optimized to access their elements by key
values. All of the STL container classes are defined in namespace std.
DO use templates whenever you have a
concept that can operate across objects
of different classes or across different
primitive data types.
DOuse the parameters to template func-
tions to narrow their instances to be
type-safe.
DOuse statics with templates as needed.
DOspecialize template behavior by over-
riding template functions by type.
DON’T stop learning about templates.
Today’s lesson has covered only some of
what you can do with templates.
Detailed coverage of templates is
beyond the scope of this book.
DON’T fret if you don’t yet fully under-
stand how to create your own templates.
It is more immediately important to
know how to use them. As you’ll see in
the next section, there are lots of exist-
ing templates for you to use in the STL.
DO DON’T