Points of Departure
Chapter 4. Lists
Whenever possible, we use lists in favor of arrays. This chapter explains ways of grouping things together in lists and how to iterate through them.
4.1. 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
A generic container is named as such because
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<double> doublList; QList<Thing> 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.
Any time you have a container of things, sooner or later you are probably going to loop through the container and do something with each thing. An
is an object that provides indirect access to each element in a container. It is
Qt 4 supports the following styles of iteration:
4.2.1. QStringList and Iteration
For text processing, it is very useful to work with lists of strings. QStringList is derived from QList<QString> so it inherits all of QList 's behavior (see Chapter 6). In addition, QStringList has some string-specific convenience functions such as indexOf() , join() , and replaceInStrings() .
Converting between lists and individual strings is quite easy with perl-like split() and join() functions. Example 4.1 demonstrates lists, iterations, split() , and join() .
Example 4.1. src/collections/lists/lists-examples.cpp
src/collections> ./collections The Spring months are: March, April, May December, January, February, March, April, May, June, July, August, September, October, November [December] [January] [February] [March] [April] [May] [June] [July] [August] [September] [October] [November] src/collections>
C++ GUI Programming with Qt 4 (2nd Edition) (Prentice Hall Open Source Software Development Series)
Design Patterns: Elements of Reusable Object-Oriented Software
Modern C++ Design: Generic Programming and Design Patterns Applied
Advanced Qt Programming: Creating Great Software with C++ and Qt 4 (Prentice Hall Open Source Software Development)