[ 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++:
Neither the compiler nor the runtime system checks array subscripts to make sure that they are within the correct 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 runtime and developer time).
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
Generics are classes or functions that accept template (Section 11.1) parameters so that they can be used with different types of data.
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.
Generated: 2012-03-02 | © 2012 Alan Ezust and Paul Ezust. |