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.

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

  1. Generics are classes or functions that accept template (see Section 10.1) parameters so that they can operate on any type.
  2. 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.

Категории