source: trunk/doc/src/frameworks-technologies/containers.qdoc@ 651

Last change on this file since 651 was 651, checked in by Dmitry A. Kuminov, 15 years ago

trunk: Merged in qt 4.6.2 sources.

  • Property svn:eol-style set to native
File size: 36.2 KB
Line 
1/****************************************************************************
2**
3** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
4** All rights reserved.
5** Contact: Nokia Corporation ([email protected])
6**
7** This file is part of the documentation of the Qt Toolkit.
8**
9** $QT_BEGIN_LICENSE:LGPL$
10** Commercial Usage
11** Licensees holding valid Qt Commercial licenses may use this file in
12** accordance with the Qt Commercial License Agreement provided with the
13** Software or, alternatively, in accordance with the terms contained in
14** a written agreement between you and Nokia.
15**
16** GNU Lesser General Public License Usage
17** Alternatively, this file may be used under the terms of the GNU Lesser
18** General Public License version 2.1 as published by the Free Software
19** Foundation and appearing in the file LICENSE.LGPL included in the
20** packaging of this file. Please review the following information to
21** ensure the GNU Lesser General Public License version 2.1 requirements
22** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
23**
24** In addition, as a special exception, Nokia gives you certain additional
25** rights. These rights are described in the Nokia Qt LGPL Exception
26** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
27**
28** GNU General Public License Usage
29** Alternatively, this file may be used under the terms of the GNU
30** General Public License version 3.0 as published by the Free Software
31** Foundation and appearing in the file LICENSE.GPL included in the
32** packaging of this file. Please review the following information to
33** ensure the GNU General Public License version 3.0 requirements will be
34** met: http://www.gnu.org/copyleft/gpl.html.
35**
36** If you have questions regarding the use of this file, please contact
37** Nokia at [email protected].
38** $QT_END_LICENSE$
39**
40****************************************************************************/
41
42/*!
43 \group tools
44 \title Non-GUI Classes
45 \ingroup groups
46
47 \brief Collection classes such as list, queue, stack and string, along
48 with other classes that can be used without needing QApplication.
49
50 The non-GUI classes are general-purpose collection and string classes
51 that may be used independently of the GUI classes.
52
53 In particular, these classes do not depend on QApplication at all,
54 and so can be used in non-GUI programs.
55
56*/
57
58/*!
59 \page containers.html
60 \title Generic Containers
61 \ingroup frameworks-technologies
62 \ingroup groups
63 \keyword container class
64 \keyword container classes
65
66 \brief Qt's template-based container classes.
67
68 \tableofcontents
69
70 \section1 Introduction
71
72 The Qt library provides a set of general purpose template-based
73 container classes. These classes can be used to store items of a
74 specified type. For example, if you need a resizable array of
75 \l{QString}s, use QVector<QString>.
76
77 These container classes are designed to be lighter, safer, and
78 easier to use than the STL containers. If you are unfamiliar with
79 the STL, or prefer to do things the "Qt way", you can use these
80 classes instead of the STL classes.
81
82 The container classes are \l{implicitly shared}, they are
83 \l{reentrant}, and they are optimized for speed, low memory
84 consumption, and minimal inline code expansion, resulting in
85 smaller executables. In addition, they are \l{thread-safe}
86 in situations where they are used as read-only containers
87 by all threads used to access them.
88
89 For traversing the items stored in a container, you can use one
90 of two types of iterators: \l{Java-style iterators} and
91 \l{STL-style iterators}. The Java-style iterators are easier to
92 use and provide high-level functionality, whereas the STL-style
93 iterators are slightly more efficient and can be used together
94 with Qt's and STL's \l{generic algorithms}.
95
96 Qt also offers a \l{foreach} keyword that make it very
97 easy to iterate over all the items stored in a container.
98
99 \section1 The Container Classes
100
101 Qt provides the following sequential containers: QList,
102 QLinkedList, QVector, QStack, and QQueue. For most
103 applications, QList is the best type to use. Although it is
104 implemented as an array-list, it provides very fast prepends and
105 appends. If you really need a linked-list, use QLinkedList; if you
106 want your items to occupy consecutive memory locations, use QVector.
107 QStack and QQueue are convenience classes that provide LIFO and
108 FIFO semantics.
109
110 Qt also provides these associative containers: QMap,
111 QMultiMap, QHash, QMultiHash, and QSet. The "Multi" containers
112 conveniently support multiple values associated with a single
113 key. The "Hash" containers provide faster lookup by using a hash
114 function instead of a binary search on a sorted set.
115
116 As special cases, the QCache and QContiguousCache classes provide
117 efficient hash-lookup of objects in a limited cache storage.
118
119 \table
120 \header \o Class \o Summary
121
122 \row \o \l{QList}<T>
123 \o This is by far the most commonly used container class. It
124 stores a list of values of a given type (T) that can be accessed
125 by index. Internally, the QList is implemented using an array,
126 ensuring that index-based access is very fast.
127
128 Items can be added at either end of the list using
129 QList::append() and QList::prepend(), or they can be inserted in
130 the middle using QList::insert(). More than any other container
131 class, QList is highly optimized to expand to as little code as
132 possible in the executable. QStringList inherits from
133 QList<QString>.
134
135 \row \o \l{QLinkedList}<T>
136 \o This is similar to QList, except that it uses
137 iterators rather than integer indexes to access items. It also
138 provides better performance than QList when inserting in the
139 middle of a huge list, and it has nicer iterator semantics.
140 (Iterators pointing to an item in a QLinkedList remain valid as
141 long as the item exists, whereas iterators to a QList can become
142 invalid after any insertion or removal.)
143
144 \row \o \l{QVector}<T>
145 \o This stores an array of values of a given type at adjacent
146 positions in memory. Inserting at the front or in the middle of
147 a vector can be quite slow, because it can lead to large numbers
148 of items having to be moved by one position in memory.
149
150 \row \o \l{QStack}<T>
151 \o This is a convenience subclass of QVector that provides
152 "last in, first out" (LIFO) semantics. It adds the following
153 functions to those already present in QVector:
154 \l{QStack::push()}{push()}, \l{QStack::pop()}{pop()},
155 and \l{QStack::top()}{top()}.
156
157 \row \o \l{QQueue}<T>
158 \o This is a convenience subclass of QList that provides
159 "first in, first out" (FIFO) semantics. It adds the following
160 functions to those already present in QList:
161 \l{QQueue::enqueue()}{enqueue()},
162 \l{QQueue::dequeue()}{dequeue()}, and \l{QQueue::head()}{head()}.
163
164 \row \o \l{QSet}<T>
165 \o This provides a single-valued mathematical set with fast
166 lookups.
167
168 \row \o \l{QMap}<Key, T>
169 \o This provides a dictionary (associative array) that maps keys
170 of type Key to values of type T. Normally each key is associated
171 with a single value. QMap stores its data in Key order; if order
172 doesn't matter QHash is a faster alternative.
173
174 \row \o \l{QMultiMap}<Key, T>
175 \o This is a convenience subclass of QMap that provides a nice
176 interface for multi-valued maps, i.e. maps where one key can be
177 associated with multiple values.
178
179 \row \o \l{QHash}<Key, T>
180 \o This has almost the same API as QMap, but provides
181 significantly faster lookups. QHash stores its data in an
182 arbitrary order.
183
184 \row \o \l{QMultiHash}<Key, T>
185 \o This is a convenience subclass of QHash that
186 provides a nice interface for multi-valued hashes.
187
188 \endtable
189
190 Containers can be nested. For example, it is perfectly possible
191 to use a QMap<QString, QList<int> >, where the key type is
192 QString and the value type QList<int>. The only pitfall is that
193 you must insert a space between the closing angle brackets (>);
194 otherwise the C++ compiler will misinterpret the two >'s as a
195 right-shift operator (>>) and report a syntax error.
196
197 The containers are defined in individual header files with the
198 same name as the container (e.g., \c <QLinkedList>). For
199 convenience, the containers are forward declared in \c
200 <QtContainerFwd>.
201
202 \keyword assignable data type
203 \keyword assignable data types
204
205 The values stored in the various containers can be of any
206 \e{assignable data type}. To qualify, a type must provide a
207 default constructor, a copy constructor, and an assignment
208 operator. This covers most data types you are likely to want to
209 store in a container, including basic types such as \c int and \c
210 double, pointer types, and Qt data types such as QString, QDate,
211 and QTime, but it doesn't cover QObject or any QObject subclass
212 (QWidget, QDialog, QTimer, etc.). If you attempt to instantiate a
213 QList<QWidget>, the compiler will complain that QWidget's copy
214 constructor and assignment operators are disabled. If you want to
215 store these kinds of objects in a container, store them as
216 pointers, for example as QList<QWidget *>.
217
218 Here's an example custom data type that meets the requirement of
219 an assignable data type:
220
221 \snippet doc/src/snippets/code/doc_src_containers.qdoc 0
222
223 If we don't provide a copy constructor or an assignment operator,
224 C++ provides a default implementation that performs a
225 member-by-member copy. In the example above, that would have been
226 sufficient. Also, if you don't provide any constructors, C++
227 provides a default constructor that initializes its member using
228 default constructors. Although it doesn't provide any
229 explicit constructors or assignment operator, the following data
230 type can be stored in a container:
231
232 \snippet doc/src/snippets/streaming/main.cpp 0
233
234 Some containers have additional requirements for the data types
235 they can store. For example, the Key type of a QMap<Key, T> must
236 provide \c operator<(). Such special requirements are documented
237 in a class's detailed description. In some cases, specific
238 functions have special requirements; these are described on a
239 per-function basis. The compiler will always emit an error if a
240 requirement isn't met.
241
242 Qt's containers provide operator<<() and operator>>() so that they
243 can easily be read and written using a QDataStream. This means
244 that the data types stored in the container must also support
245 operator<<() and operator>>(). Providing such support is
246 straightforward; here's how we could do it for the Movie struct
247 above:
248
249 \snippet doc/src/snippets/streaming/main.cpp 1
250 \codeline
251 \snippet doc/src/snippets/streaming/main.cpp 2
252
253 \keyword default-constructed values
254
255 The documentation of certain container class functions refer to
256 \e{default-constructed values}; for example, QVector
257 automatically initializes its items with default-constructed
258 values, and QMap::value() returns a default-constructed value if
259 the specified key isn't in the map. For most value types, this
260 simply means that a value is created using the default
261 constructor (e.g. an empty string for QString). But for primitive
262 types like \c{int} and \c{double}, as well as for pointer types,
263 the C++ language doesn't specify any initialization; in those
264 cases, Qt's containers automatically initialize the value to 0.
265
266 \section1 The Iterator Classes
267
268 Iterators provide a uniform means to access items in a container.
269 Qt's container classes provide two types of iterators: Java-style
270 iterators and STL-style iterators. Iterators of both types are
271 invalidated when the data in the container is modified or detached
272 from \l{Implicit Sharing}{implicitly shared copies} due to a call
273 to a non-const member function.
274
275 \section2 Java-Style Iterators
276
277 The Java-style iterators are new in Qt 4 and are the standard
278 ones used in Qt applications. They are more convenient to use than
279 the STL-style iterators, at the price of being slightly less
280 efficient. Their API is modelled on Java's iterator classes.
281
282 For each container class, there are two Java-style iterator data
283 types: one that provides read-only access and one that provides
284 read-write access.
285
286 \table
287 \header \o Containers \o Read-only iterator
288 \o Read-write iterator
289 \row \o QList<T>, QQueue<T> \o QListIterator<T>
290 \o QMutableListIterator<T>
291 \row \o QLinkedList<T> \o QLinkedListIterator<T>
292 \o QMutableLinkedListIterator<T>
293 \row \o QVector<T>, QStack<T> \o QVectorIterator<T>
294 \o QMutableVectorIterator<T>
295 \row \o QSet<T> \o QSetIterator<T>
296 \o QMutableSetIterator<T>
297 \row \o QMap<Key, T>, QMultiMap<Key, T> \o QMapIterator<Key, T>
298 \o QMutableMapIterator<Key, T>
299 \row \o QHash<Key, T>, QMultiHash<Key, T> \o QHashIterator<Key, T>
300 \o QMutableHashIterator<Key, T>
301 \endtable
302
303 In this discussion, we will concentrate on QList and QMap. The
304 iterator types for QLinkedList, QVector, and QSet have exactly
305 the same interface as QList's iterators; similarly, the iterator
306 types for QHash have the same interface as QMap's iterators.
307
308 Unlike STL-style iterators (covered \l{STL-style
309 iterators}{below}), Java-style iterators point \e between items
310 rather than directly \e at items. For this reason, they are
311 either pointing to the very beginning of the container (before
312 the first item), at the very end of the container (after the last
313 item), or between two items. The diagram below shows the valid
314 iterator positions as red arrows for a list containing four
315 items:
316
317 \img javaiterators1.png
318
319 Here's a typical loop for iterating through all the elements of a
320 QList<QString> in order and printing them to the console:
321
322 \snippet doc/src/snippets/code/doc_src_containers.qdoc 1
323
324 It works as follows: The QList to iterate over is passed to the
325 QListIterator constructor. At that point, the iterator is located
326 just in front of the first item in the list (before item "A").
327 Then we call \l{QListIterator::hasNext()}{hasNext()} to
328 check whether there is an item after the iterator. If there is, we
329 call \l{QListIterator::next()}{next()} to jump over that
330 item. The next() function returns the item that it jumps over. For
331 a QList<QString>, that item is of type QString.
332
333 Here's how to iterate backward in a QList:
334
335 \snippet doc/src/snippets/code/doc_src_containers.qdoc 2
336
337 The code is symmetric with iterating forward, except that we
338 start by calling \l{QListIterator::toBack()}{toBack()}
339 to move the iterator after the last item in the list.
340
341 The diagram below illustrates the effect of calling
342 \l{QListIterator::next()}{next()} and
343 \l{QListIterator::previous()}{previous()} on an iterator:
344
345 \img javaiterators2.png
346
347 The following table summarizes the QListIterator API:
348
349 \table
350 \header \o Function \o Behavior
351 \row \o \l{QListIterator::toFront()}{toFront()}
352 \o Moves the iterator to the front of the list (before the first item)
353 \row \o \l{QListIterator::toBack()}{toBack()}
354 \o Moves the iterator to the back of the list (after the last item)
355 \row \o \l{QListIterator::hasNext()}{hasNext()}
356 \o Returns true if the iterator isn't at the back of the list
357 \row \o \l{QListIterator::next()}{next()}
358 \o Returns the next item and advances the iterator by one position
359 \row \o \l{QListIterator::peekNext()}{peekNext()}
360 \o Returns the next item without moving the iterator
361 \row \o \l{QListIterator::hasPrevious()}{hasPrevious()}
362 \o Returns true if the iterator isn't at the front of the list
363 \row \o \l{QListIterator::previous()}{previous()}
364 \o Returns the previous item and moves the iterator back by one position
365 \row \o \l{QListIterator::peekPrevious()}{peekPrevious()}
366 \o Returns the previous item without moving the iterator
367 \endtable
368
369 QListIterator provides no functions to insert or remove items
370 from the list as we iterate. To accomplish this, you must use
371 QMutableListIterator. Here's an example where we remove all
372 odd numbers from a QList<int> using QMutableListIterator:
373
374 \snippet doc/src/snippets/code/doc_src_containers.qdoc 3
375
376 The next() call in the loop is made every time. It jumps over the
377 next item in the list. The
378 \l{QMutableListIterator::remove()}{remove()} function removes the
379 last item that we jumped over from the list. The call to
380 \l{QMutableListIterator::remove()}{remove()} does not invalidate
381 the iterator, so it is safe to continue using it. This works just
382 as well when iterating backward:
383
384 \snippet doc/src/snippets/code/doc_src_containers.qdoc 4
385
386 If we just want to modify the value of an existing item, we can
387 use \l{QMutableListIterator::setValue()}{setValue()}. In the code
388 below, we replace any value larger than 128 with 128:
389
390 \snippet doc/src/snippets/code/doc_src_containers.qdoc 5
391
392 Just like \l{QMutableListIterator::remove()}{remove()},
393 \l{QMutableListIterator::setValue()}{setValue()} operates on the
394 last item that we jumped over. If we iterate forward, this is the
395 item just before the iterator; if we iterate backward, this is
396 the item just after the iterator.
397
398 The \l{QMutableListIterator::next()}{next()} function returns a
399 non-const reference to the item in the list. For simple
400 operations, we don't even need
401 \l{QMutableListIterator::setValue()}{setValue()}:
402
403 \snippet doc/src/snippets/code/doc_src_containers.qdoc 6
404
405 As mentioned above, QLinkedList's, QVector's, and QSet's iterator
406 classes have exactly the same API as QList's. We will now turn to
407 QMapIterator, which is somewhat different because it iterates on
408 (key, value) pairs.
409
410 Like QListIterator, QMapIterator provides
411 \l{QMapIterator::toFront()}{toFront()},
412 \l{QMapIterator::toBack()}{toBack()},
413 \l{QMapIterator::hasNext()}{hasNext()},
414 \l{QMapIterator::next()}{next()},
415 \l{QMapIterator::peekNext()}{peekNext()},
416 \l{QMapIterator::hasPrevious()}{hasPrevious()},
417 \l{QMapIterator::previous()}{previous()}, and
418 \l{QMapIterator::peekPrevious()}{peekPrevious()}. The key and
419 value components are extracted by calling key() and value() on
420 the object returned by next(), peekNext(), previous(), or
421 peekPrevious().
422
423 The following example removes all (capital, country) pairs where
424 the capital's name ends with "City":
425
426 \snippet doc/src/snippets/code/doc_src_containers.qdoc 7
427
428 QMapIterator also provides a key() and a value() function that
429 operate directly on the iterator and that return the key and
430 value of the last item that the iterator jumped above. For
431 example, the following code copies the contents of a QMap into a
432 QHash:
433
434 \snippet doc/src/snippets/code/doc_src_containers.qdoc 8
435
436 If we want to iterate through all the items with the same
437 value, we can use \l{QMapIterator::findNext()}{findNext()}
438 or \l{QMapIterator::findPrevious()}{findPrevious()}.
439 Here's an example where we remove all the items with a particular
440 value:
441
442 \snippet doc/src/snippets/code/doc_src_containers.qdoc 9
443
444 \section2 STL-Style Iterators
445
446 STL-style iterators have been available since the release of Qt
447 2.0. They are compatible with Qt's and STL's \l{generic
448 algorithms} and are optimized for speed.
449
450 For each container class, there are two STL-style iterator types:
451 one that provides read-only access and one that provides
452 read-write access. Read-only iterators should be used wherever
453 possible because they are faster than read-write iterators.
454
455 \table
456 \header \o Containers \o Read-only iterator
457 \o Read-write iterator
458 \row \o QList<T>, QQueue<T> \o QList<T>::const_iterator
459 \o QList<T>::iterator
460 \row \o QLinkedList<T> \o QLinkedList<T>::const_iterator
461 \o QLinkedList<T>::iterator
462 \row \o QVector<T>, QStack<T> \o QVector<T>::const_iterator
463 \o QVector<T>::iterator
464 \row \o QSet<T> \o QSet<T>::const_iterator
465 \o QSet<T>::iterator
466 \row \o QMap<Key, T>, QMultiMap<Key, T> \o QMap<Key, T>::const_iterator
467 \o QMap<Key, T>::iterator
468 \row \o QHash<Key, T>, QMultiHash<Key, T> \o QHash<Key, T>::const_iterator
469 \o QHash<Key, T>::iterator
470 \endtable
471
472 The API of the STL iterators is modelled on pointers in an array.
473 For example, the \c ++ operator advances the iterator to the next
474 item, and the \c * operator returns the item that the iterator
475 points to. In fact, for QVector and QStack, which store their
476 items at adjacent memory positions, the
477 \l{QVector::iterator}{iterator} type is just a typedef for \c{T *},
478 and the \l{QVector::iterator}{const_iterator} type is
479 just a typedef for \c{const T *}.
480
481 In this discussion, we will concentrate on QList and QMap. The
482 iterator types for QLinkedList, QVector, and QSet have exactly
483 the same interface as QList's iterators; similarly, the iterator
484 types for QHash have the same interface as QMap's iterators.
485
486 Here's a typical loop for iterating through all the elements of a
487 QList<QString> in order and converting them to lowercase:
488
489 \snippet doc/src/snippets/code/doc_src_containers.qdoc 10
490
491 Unlike \l{Java-style iterators}, STL-style iterators point
492 directly at items. The begin() function of a container returns an
493 iterator that points to the first item in the container. The
494 end() function of a container returns an iterator to the
495 imaginary item one position past the last item in the container.
496 end() marks an invalid position; it must never be dereferenced.
497 It is typically used in a loop's break condition. If the list is
498 empty, begin() equals end(), so we never execute the loop.
499
500 The diagram below shows the valid iterator positions as red
501 arrows for a vector containing four items:
502
503 \img stliterators1.png
504
505 Iterating backward with an STL-style iterator requires us to
506 decrement the iterator \e before we access the item. This
507 requires a \c while loop:
508
509 \snippet doc/src/snippets/code/doc_src_containers.qdoc 11
510
511 In the code snippets so far, we used the unary \c * operator to
512 retrieve the item (of type QString) stored at a certain iterator
513 position, and we then called QString::toLower() on it. Most C++
514 compilers also allow us to write \c{i->toLower()}, but some
515 don't.
516
517 For read-only access, you can use const_iterator, constBegin(),
518 and constEnd(). For example:
519
520 \snippet doc/src/snippets/code/doc_src_containers.qdoc 12
521
522 The following table summarizes the STL-style iterators' API:
523
524 \table
525 \header \o Expression \o Behavior
526 \row \o \c{*i} \o Returns the current item
527 \row \o \c{++i} \o Advances the iterator to the next item
528 \row \o \c{i += n} \o Advances the iterator by \c n items
529 \row \o \c{--i} \o Moves the iterator back by one item
530 \row \o \c{i -= n} \o Moves the iterator back by \c n items
531 \row \o \c{i - j} \o Returns the number of items between iterators \c i and \c j
532 \endtable
533
534 The \c{++} and \c{--} operators are available both as prefix
535 (\c{++i}, \c{--i}) and postfix (\c{i++}, \c{i--}) operators. The
536 prefix versions modify the iterators and return a reference to
537 the modified iterator; the postfix versions take a copy of the
538 iterator before they modify it, and return that copy. In
539 expressions where the return value is ignored, we recommend that
540 you use the prefix operators (\c{++i}, \c{--i}), as these are
541 slightly faster.
542
543 For non-const iterator types, the return value of the unary \c{*}
544 operator can be used on the left side of the assignment operator.
545
546 For QMap and QHash, the \c{*} operator returns the value
547 component of an item. If you want to retrieve the key, call key()
548 on the iterator. For symmetry, the iterator types also provide a
549 value() function to retrieve the value. For example, here's how
550 we would print all items in a QMap to the console:
551
552 \snippet doc/src/snippets/code/doc_src_containers.qdoc 13
553
554 Thanks to \l{implicit sharing}, it is very inexpensive for a
555 function to return a container per value. The Qt API contains
556 dozens of functions that return a QList or QStringList per value
557 (e.g., QSplitter::sizes()). If you want to iterate over these
558 using an STL iterator, you should always take a copy of the
559 container and iterate over the copy. For example:
560
561 \snippet doc/src/snippets/code/doc_src_containers.qdoc 14
562
563 This problem doesn't occur with functions that return a const or
564 non-const reference to a container.
565
566 \l{Implicit sharing} has another consequence on STL-style
567 iterators: You must not take a copy of a container while
568 non-const iterators are active on that container. Java-style
569 iterators don't suffer from that limitation.
570
571 \keyword foreach
572 \section1 The foreach Keyword
573
574 If you just want to iterate over all the items in a container
575 in order, you can use Qt's \c foreach keyword. The keyword is a
576 Qt-specific addition to the C++ language, and is implemented
577 using the preprocessor.
578
579 Its syntax is: \c foreach (\e variable, \e container) \e
580 statement. For example, here's how to use \c foreach to iterate
581 over a QLinkedList<QString>:
582
583 \snippet doc/src/snippets/code/doc_src_containers.qdoc 15
584
585 The \c foreach code is significantly shorter than the equivalent
586 code that uses iterators:
587
588 \snippet doc/src/snippets/code/doc_src_containers.qdoc 16
589
590 Unless the data type contains a comma (e.g., \c{QPair<int,
591 int>}), the variable used for iteration can be defined within the
592 \c foreach statement:
593
594 \snippet doc/src/snippets/code/doc_src_containers.qdoc 17
595
596 And like any other C++ loop construct, you can use braces around
597 the body of a \c foreach loop, and you can use \c break to leave
598 the loop:
599
600 \snippet doc/src/snippets/code/doc_src_containers.qdoc 18
601
602 With QMap and QHash, \c foreach accesses the value component of
603 the (key, value) pairs. If you want to iterate over both the keys
604 and the values, you can use iterators (which are fastest), or you
605 can write code like this:
606
607 \snippet doc/src/snippets/code/doc_src_containers.qdoc 19
608
609 For a multi-valued map:
610
611 \snippet doc/src/snippets/code/doc_src_containers.qdoc 20
612
613 Qt automatically takes a copy of the container when it enters a
614 \c foreach loop. If you modify the container as you are
615 iterating, that won't affect the loop. (If you don't modify the
616 container, the copy still takes place, but thanks to \l{implicit
617 sharing} copying a container is very fast.) Similarly, declaring
618 the variable to be a non-const reference, in order to modify the
619 current item in the list will not work either.
620
621 In addition to \c foreach, Qt also provides a \c forever
622 pseudo-keyword for infinite loops:
623
624 \snippet doc/src/snippets/code/doc_src_containers.qdoc 21
625
626 If you're worried about namespace pollution, you can disable
627 these macros by adding the following line to your \c .pro file:
628
629 \snippet doc/src/snippets/code/doc_src_containers.qdoc 22
630
631 \section1 Other Container-Like Classes
632
633 Qt includes three template classes that resemble containers in
634 some respects. These classes don't provide iterators and cannot
635 be used with the \c foreach keyword.
636
637 \list
638 \o QVarLengthArray<T, Prealloc> provides a low-level
639 variable-length array. It can be used instead of QVector in
640 places where speed is particularly important.
641
642 \o QCache<Key, T> provides a cache to store objects of a certain
643 type T associated with keys of type Key.
644
645 \o QContiguousCache<T> provides an efficient way of caching data
646 that is typically accessed in a contiguous way.
647
648 \o QPair<T1, T2> stores a pair of elements.
649 \endlist
650
651 Additional non-template types that compete with Qt's template
652 containers are QBitArray, QByteArray, QString, and QStringList.
653
654 \section1 Algorithmic Complexity
655
656 Algorithmic complexity is concerned about how fast (or slow) each
657 function is as the number of items in the container grow. For
658 example, inserting an item in the middle of a QLinkedList is an
659 extremely fast operation, irrespective of the number of items
660 stored in the QLinkedList. On the other hand, inserting an item
661 in the middle of a QVector is potentially very expensive if the
662 QVector contains many items, since half of the items must be
663 moved one position in memory.
664
665 To describe algorithmic complexity, we use the following
666 terminology, based on the "big Oh" notation:
667
668 \keyword constant time
669 \keyword logarithmic time
670 \keyword linear time
671 \keyword linear-logarithmic time
672 \keyword quadratic time
673
674 \list
675 \o \bold{Constant time:} O(1). A function is said to run in constant
676 time if it requires the same amount of time no matter how many
677 items are present in the container. One example is
678 QLinkedList::insert().
679
680 \o \bold{Logarithmic time:} O(log \e n). A function that runs in
681 logarithmic time is a function whose running time is
682 proportional to the logarithm of the number of items in the
683 container. One example is qBinaryFind().
684
685 \o \bold{Linear time:} O(\e n). A function that runs in linear time
686 will execute in a time directly proportional to the number of
687 items stored in the container. One example is
688 QVector::insert().
689
690 \o \bold{Linear-logarithmic time:} O(\e{n} log \e n). A function
691 that runs in linear-logarithmic time is asymptotically slower
692 than a linear-time function, but faster than a quadratic-time
693 function.
694
695 \o \bold{Quadratic time:} O(\e{n}\unicode{178}). A quadratic-time function
696 executes in a time that is proportional to the square of the
697 number of items stored in the container.
698 \endlist
699
700 The following table summarizes the algorithmic complexity of Qt's
701 sequential container classes:
702
703 \table
704 \header \o \o Index lookup \o Insertion \o Prepending \o Appending
705 \row \o QLinkedList<T> \o O(\e n) \o O(1) \o O(1) \o O(1)
706 \row \o QList<T> \o O(1) \o O(n) \o Amort. O(1) \o Amort. O(1)
707 \row \o QVector<T> \o O(1) \o O(n) \o O(n) \o Amort. O(1)
708 \endtable
709
710 In the table, "Amort." stands for "amortized behavior". For
711 example, "Amort. O(1)" means that if you call the function
712 only once, you might get O(\e n) behavior, but if you call it
713 multiple times (e.g., \e n times), the average behavior will be
714 O(1).
715
716 The following table summarizes the algorithmic complexity of Qt's
717 associative containers and sets:
718
719 \table
720 \header \o{1,2} \o{2,1} Key lookup \o{2,1} Insertion
721 \header \o Average \o Worst case \o Average \o Worst case
722 \row \o QMap<Key, T> \o O(log \e n) \o O(log \e n) \o O(log \e n) \o O(log \e n)
723 \row \o QMultiMap<Key, T> \o O(log \e n) \o O(log \e n) \o O(log \e n) \o O(log \e n)
724 \row \o QHash<Key, T> \o Amort. O(1) \o O(\e n) \o Amort. O(1) \o O(\e n)
725 \row \o QSet<Key> \o Amort. O(1) \o O(\e n) \o Amort. O(1) \o O(\e n)
726 \endtable
727
728 With QVector, QHash, and QSet, the performance of appending items
729 is amortized O(log \e n). It can be brought down to O(1) by
730 calling QVector::reserve(), QHash::reserve(), or QSet::reserve()
731 with the expected number of items before you insert the items.
732 The next section discusses this topic in more depth.
733
734 \section1 Growth Strategies
735
736 QVector<T>, QString, and QByteArray store their items
737 contiguously in memory; QList<T> maintains an array of pointers
738 to the items it stores to provide fast index-based access (unless
739 T is a pointer type or a basic type of the size of a pointer, in
740 which case the value itself is stored in the array); QHash<Key,
741 T> keeps a hash table whose size is proportional to the number
742 of items in the hash. To avoid reallocating the data every single
743 time an item is added at the end of the container, these classes
744 typically allocate more memory than necessary.
745
746 Consider the following code, which builds a QString from another
747 QString:
748
749 \snippet doc/src/snippets/code/doc_src_containers.qdoc 23
750
751 We build the string \c out dynamically by appending one character
752 to it at a time. Let's assume that we append 15000 characters to
753 the QString string. Then the following 18 reallocations (out of a
754 possible 15000) occur when QString runs out of space: 4, 8, 12,
755 16, 20, 52, 116, 244, 500, 1012, 2036, 4084, 6132, 8180, 10228,
756 12276, 14324, 16372. At the end, the QString has 16372 Unicode
757 characters allocated, 15000 of which are occupied.
758
759 The values above may seem a bit strange, but here are the guiding
760 principles:
761 \list
762 \o QString allocates 4 characters at a time until it reaches size 20.
763 \o From 20 to 4084, it advances by doubling the size each time.
764 More precisely, it advances to the next power of two, minus
765 12. (Some memory allocators perform worst when requested exact
766 powers of two, because they use a few bytes per block for
767 book-keeping.)
768 \o From 4084 on, it advances by blocks of 2048 characters (4096
769 bytes). This makes sense because modern operating systems
770 don't copy the entire data when reallocating a buffer; the
771 physical memory pages are simply reordered, and only the data
772 on the first and last pages actually needs to be copied.
773 \endlist
774
775 QByteArray and QList<T> use more or less the same algorithm as
776 QString.
777
778 QVector<T> also uses that algorithm for data types that can be
779 moved around in memory using memcpy() (including the basic C++
780 types, the pointer types, and Qt's \l{shared classes}) but uses a