Qt 4: The book

Page 398

B Tulip: Containers and Algorithms

using namespace std; int main() { QStringList list; list << "dog" << "cat" << "mouse"; QStringList::iterator it; for (it = list.begin(); it != list.end(); ++it) { qDebug() << *it << endl; } return 0; }

If you apply the * operator to it, you will reach the list element to which the iterator currently points, since Qt overloads the operator * for iterators for this purpose. In such for loops you must remember to use the pre-increment operator (++it) instead of the usual it++: This operator works without an unnecessary temporary object for each for loop. If the elements accessed in the loop should only be read but not modiďŹ ed, a const_iterator is used, which ensures improved performance.

B.1.2

Java-Style Iterators

Apart from the STL iterators, Qt also has Java-style iterators. Those are self-contained classes which Trolltech has named according to the pattern Qcontainernameiterator. Conceptually, Java iterators are fundamentally different from STL iterators in a number of ways. For one thing, they point between two elements of a data structure, and not to one of them. This results in Java iterators often being easier to handle, but somewhat slower than their STL-compatible colleagues. Another difference is that by default they do not allow write access to the data structure, in contrast to their brothers of the same kind in the STL world. There are two reasons for this. On one hand, data structures are more often read than written during traversal. An immutable (that is, an unchangeable) Java iterator or const iterator (STL) saves time through this. On the other hand, an immutable iterator ensures that the data cannot be changed by an error in the program. To obtain write access to the elements of the data structure, changeable iterators, or mutable iterators, are used. For QList-based lists the changeable iterator is called, for example, QMutableListIterator. The following example shows how Java-style iterators are handled. It operates on an existing integer QList called list: QListIterator<int> i(list);

396


Issuu converts static files into: digital portfolios, online yearbooks, online catalogs, digital photo albums and more. Sign up and create your flipbook.