4.1. Introduction to Containers

[ fromfile: lists.xml id: introcontainers ]

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 (Section 21.4) to store such collections. In C++ arrays are regarded as evil.

Following are a few good reasons to avoid using arrays in C++:

The Standard Library and Qt both provide the programmer with lists that safely resize themselves as needed and also perform range checking. std::list and QList are the most basic generic containers in their respective libraries. They are similar to each other in interface (the way they are used from client code). They differ in implementation (the way they behave at runtime). Both libraries also provide several other generic containers that are optimized for particular types of application.

We used the term generic containers because

  1. Generics are classes or functions that accept template (Section 11.1) parameters so that they can be used with different types of data.

  2. Containers (Section 6.8) are objects that can contain other objects.

To use a generic container, client code must contain a declaration that answers the question: "Container of what?" For example:

  QList<double>  doubleList;
  QList<Thing>  thingList;

QList supports many operations. As with any class you reuse, we recommend that you read 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.