| I l @ ve RuBoard |
24.9 Summary
Templates provide a
When you do get templates working, the result can be some very powerful code. An example of this is the Standard Template Library (see Chapter 25). |
| I l @ ve RuBoard |
| I l @ ve RuBoard |
24.10 Programming ExercisesExercise 24-1: Write a template min that returns the minimum of two values. Make sure you handle C-style strings correctly. Exercise 24-2: Write a template class to implement an array with bounds checking. Exercise 24-3: Define a template class that implements a set. The class allows you to set, clear, and test elements. (An integer version of this class was presented in Exercise 13-4.) |
| I l @ ve RuBoard |
| I l @ ve RuBoard |
Chapter 25. Standard Template Library
As people
These containers are designed as templates so that they can hold almost anything. The library provides not only the containers but also iterators that make access to the contents of a container easier. Finally, there are the algorithms that perform common functions on a container, such as sorting, merging two containers, locating elements, and other such functions. |
| I l @ ve RuBoard |
| I l @ ve RuBoard |
25.1 STL BasicsIn this section we take a look at the basic concepts that went into the design of the STL and how all these design elements come together to provide a very robust and flexible way of handling items. 25.1.1 Containers
The
The STL divides containers into sequences, which store their elements in order, and associative containers, in which elements are accessed using a key value. The basic STL containers are:
These containers give you a way of storing most data in almost any way you want to. Now that we've got our data stored, we need access to it. 25.1.2 Iterators
Iterators allow you to go through a container and access the data inside. One form of this is the forward iterator, which allows you to access each element from first to last. There is a reverse iterator that allows you to go the other way and a bidirectional iterator, which goes both ways. Finally, there is the random access iterator, which allows you to access any element
Not all containers support all iterator types. For example, the vector supports random access iterators, while the list container does not. We'll see how to use iterators in the class program described later in this chapter. 25.1.3 Algorithms
We have containers to hold the data and iterators so we can access it. For example, the
These three elements ”containers, iterators, and algorithms ”make up the STL. Now that we know the basics, let's see how to use this library in the real world. |
| I l @ ve RuBoard |