Sams Teach Yourself C++ in 21 Days

(singke) #1

Understanding Sequence Containers..............................................................


The Standard Template Library sequence containers provide efficient sequential access to
a list of objects. The Standard C++ Library provides five sequence containers:vector,
list,stack,deque, and queue.

The Vector Container
You often use arrays to store and access a number of elements. Elements in an array are
of the same type and are accessed with an index. The STL provides a container class
vectorthat behaves like an array but that is more powerful and safer to use than the
standard C++ array.
A vectoris a container optimized to provide fast access to its elements by an index. The
container class vectoris defined in the header file <vector>in namespace std(see Day
18, “Creating and Using Namespaces,” for more information on the use of namespaces).
A vector can grow itself as necessary. Suppose that you have created a vector to contain
10 elements. After you have filled the vector with 10 objects, the vector is full. If you
then add another object to the vector, the vector automatically increases its capacity so
that it can accommodate the eleventh object. Here is how the vectorclass is defined:
template <class T, class Allocator = allocator<T>> class vector
{
// class members
};
The first argument (class T) is the type of the elements in the vector. The second argu-
ment (class Allocator) is an allocator class. Allocatorsare memory managers respon-
sible for the memory allocation and deallocation of elements for the containers. The
concept and implementation of allocators are advanced topics that are beyond the scope
of this book.
By default, elements are created using the operatornew()and are freed using the opera-
tordelete(). That is, the default constructor of class Tis called to create a new element.
This provides another argument in favor of explicitly defining a default constructor for
your own classes. If you do not, you cannot use the standard vector container to hold a
set of instances of your class.
You can define vectors that hold integers and floats as follows:
vector<int> vInts; // vector holding int elements
vector<float> vFloats; // vector holding float elements
Usually, you would have some idea as to how many elements a vector will contain. For
instance, suppose that in your school, the maximum number of students is 50. To create a
vector of students in a class, you will want the vector to be large enough to contain 50

694 Day 19

Free download pdf