Introduction to Containers

There are many occasions when it is necessary to deal with collections of things. The classic approach in languages like C is to use arrays to store such collections. In C++ arrays are regarded as evil. Here are a few good reasons to avoid using arrays.

Array subscripts are not checked to make sure that they are not out of range. A programmer using an array has the responsibility to write extra code to do the range checking.

Arrays are either fixed in size or they must use dynamic memory from the heap. With heap arrays, the programmer is responsible for making sure that, under all possible circumstances, the memory gets properly deallocated when the array is destroyed. To do this properly requires deep knowledge of C++, exceptions, and what happens under exceptional circumstances.

Inserting, prepending, or appending elements to an array can be expensive operations (in terms of both run time and developer time).

The Standard Library and Qt both provide the programmer with lists that resize themselves as needed and also perform range checking. std::list and QList are each considered basic generic containers in their respective libraries. They are similar to each other in interface (the way they are used from client code), but very different in implementation (the way they behave at runtime).

A generic container is named as such because

Generics are classes or functions that accept template (see Section 10.1) parameters so that they can operate on any type.

Containers (see Section 10.2) are objects that can contain other objects.

To use a QList, the client code must contain a declaration that answers the question: "List of what?" Like other generic containers, QList is a template class (see Chapter 10) and must be declared in the following way.

QList doublList;
QList thingList;

QList supports many operations. As with any class you reuse, it is recommended that you scan the API docs to get an overview of its full capabilities. With a single function call, items can be added, removed, swapped, queried, cleared, moved, located, and counted in a variety of ways.