1
/****************************************************************************
3
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
4
** Contact: Nokia Corporation (qt-info@nokia.com)
6
** This file is part of the documentation of the Qt Toolkit.
8
** $QT_BEGIN_LICENSE:LGPL$
10
** Licensees holding valid Qt Commercial licenses may use this file in
11
** accordance with the Qt Commercial License Agreement provided with the
12
** Software or, alternatively, in accordance with the terms contained in
13
** a written agreement between you and Nokia.
15
** GNU Lesser General Public License Usage
16
** Alternatively, this file may be used under the terms of the GNU Lesser
17
** General Public License version 2.1 as published by the Free Software
18
** Foundation and appearing in the file LICENSE.LGPL included in the
19
** packaging of this file. Please review the following information to
20
** ensure the GNU Lesser General Public License version 2.1 requirements
21
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
23
** In addition, as a special exception, Nokia gives you certain
24
** additional rights. These rights are described in the Nokia Qt LGPL
25
** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this
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.
36
** If you are unsure which license is appropriate for your use, please
37
** contact the sales department at http://www.qtsoftware.com/contact.
40
****************************************************************************/
43
\headerfile <QtAlgorithms>
44
\title Generic Algorithms
47
\brief The <QtAlgorithms> header provides generic template-based algorithms.
49
Qt provides a number of global template functions in \c
50
<QtAlgorithms> that work on containers and perform well-know
51
algorithms. You can use these algorithms with any \l {container
52
class} that provides STL-style iterators, including Qt's QList,
53
QLinkedList, QVector, QMap, and QHash classes.
55
These functions have taken their inspiration from similar
56
functions available in the STL \c <algorithm> header. Most of them
57
have a direct STL equivalent; for example, qCopyBackward() is the
58
same as STL's copy_backward() algorithm.
60
If STL is available on all your target platforms, you can use the
61
STL algorithms instead of their Qt counterparts. One reason why
62
you might want to use the STL algorithms is that STL provides
63
dozens and dozens of algorithms, whereas Qt only provides the most
64
important ones, making no attempt to duplicate functionality that
65
is already provided by the C++ standard.
67
Most algorithms take \l {STL-style iterators} as parameters. The
68
algorithms are generic in the sense that they aren't bound to a
69
specific iterator class; you can use them with any iterators that
70
meet a certain set of requirements.
72
Let's take the qFill() algorithm as an example. Unlike QVector,
73
QList has no fill() function that can be used to fill a list with
74
a particular value. If you need that functionality, you can use
77
\snippet doc/src/snippets/code/doc_src_qalgorithms.qdoc 0
79
qFill() takes a begin iterator, an end iterator, and a value.
80
In the example above, we pass \c list.begin() and \c list.end()
81
as the begin and end iterators, but this doesn't have to be
84
\snippet doc/src/snippets/code/doc_src_qalgorithms.qdoc 1
86
Different algorithms can have different requirements for the
87
iterators they accept. For example, qFill() accepts two
88
\l {forward iterators}. The iterator types required are specified
89
for each algorithm. If an iterator of the wrong type is passed (for
90
example, if QList::ConstIterator is passed as an \l {output
91
iterator}), you will always get a compiler error, although not
92
necessarily a very informative one.
94
Some algorithms have special requirements on the value type
95
stored in the containers. For example, qEqual() requires that the
96
value type supports operator==(), which it uses to compare items.
97
Similarly, qDeleteAll() requires that the value type is a
98
non-const pointer type (for example, QWidget *). The value type
99
requirements are specified for each algorithm, and the compiler
100
will produce an error if a requirement isn't met.
102
\target binaryFind example
104
The generic algorithms can be used on other container classes
105
than those provided by Qt and STL. The syntax of STL-style
106
iterators is modeled after C++ pointers, so it's possible to use
107
plain arrays as containers and plain pointers as iterators. A
108
common idiom is to use qBinaryFind() together with two static
109
arrays: one that contains a list of keys, and another that
110
contains a list of associated values. For example, the following
111
code will look up an HTML entity (e.g., \c &) in the \c
112
name_table array and return the corresponding Unicode value from
113
the \c value_table if the entity is recognized:
115
\snippet doc/src/snippets/code/doc_src_qalgorithms.qdoc 2
117
This kind of code is for advanced users only; for most
118
applications, a QMap- or QHash-based approach would work just as
121
\snippet doc/src/snippets/code/doc_src_qalgorithms.qdoc 3
123
\section1 Types of Iterators
125
The algorithms have certain requirements on the iterator types
126
they accept, and these are specified individually for each
127
function. The compiler will produce an error if a requirement
130
\section2 Input Iterators
132
An \e{input iterator} is an iterator that can be used for reading
133
data sequentially from a container. It must provide the following
134
operators: \c{==} and \c{!=} for comparing two iterators, unary
135
\c{*} for retrieving the value stored in the item, and prefix
136
\c{++} for advancing to the next item.
138
The Qt containers' iterator types (const and non-const) are all
141
\section2 Output Iterators
143
An \e{output iterator} is an iterator that can be used for
144
writing data sequentially to a container or to some output
145
stream. It must provide the following operators: unary \c{*} for
146
writing a value (i.e., \c{*it = val}) and prefix \c{++} for
147
advancing to the next item.
149
The Qt containers' non-const iterator types are all output
152
\section2 Forward Iterators
154
A \e{forward iterator} is an iterator that meets the requirements
155
of both input iterators and output iterators.
157
The Qt containers' non-const iterator types are all forward
160
\section2 Bidirectional Iterators
162
A \e{bidirectional iterator} is an iterator that meets the
163
requirements of forward iterators but that in addition supports
164
prefix \c{--} for iterating backward.
166
The Qt containers' non-const iterator types are all bidirectional
169
\section2 Random Access Iterators
171
The last category, \e{random access iterators}, is the most
172
powerful type of iterator. It supports all the requirements of a
173
bidirectional iterator, and supports the following operations:
176
\row \i \c{i += n} \i advances iterator \c i by \c n positions
177
\row \i \c{i -= n} \i moves iterator \c i back by \c n positions
178
\row \i \c{i + n} or \c{n + i} \i returns the iterator for the item \c
179
n positions ahead of iterator \c i
180
\row \i \c{i - n} \i returns the iterator for the item \c n positions behind of iterator \c i
181
\row \i \c{i - j} \i returns the number of items between iterators \c i and \c j
182
\row \i \c{i[n]} \i same as \c{*(i + n)}
183
\row \i \c{i < j} \i returns true if iterator \c j comes after iterator \c i
186
QList and QVector's non-const iterator types are random access iterators.
188
\sa {container classes}, <QtGlobal>
191
/*! \fn OutputIterator qCopy(InputIterator begin1, InputIterator end1, OutputIterator begin2)
192
\relates <QtAlgorithms>
194
Copies the items from range [\a begin1, \a end1) to range [\a
195
begin2, ...), in the order in which they appear.
197
The item at position \a begin1 is assigned to that at position \a
198
begin2; the item at position \a begin1 + 1 is assigned to that at
199
position \a begin2 + 1; and so on.
202
\snippet doc/src/snippets/code/doc_src_qalgorithms.qdoc 4
204
\sa qCopyBackward(), {input iterators}, {output iterators}
207
/*! \fn BiIterator2 qCopyBackward(BiIterator1 begin1, BiIterator1 end1, BiIterator2 end2)
208
\relates <QtAlgorithms>
210
Copies the items from range [\a begin1, \a end1) to range [...,
213
The item at position \a end1 - 1 is assigned to that at position
214
\a end2 - 1; the item at position \a end1 - 2 is assigned to that
215
at position \a end2 - 2; and so on.
218
\snippet doc/src/snippets/code/doc_src_qalgorithms.qdoc 5
220
\sa qCopy(), {bidirectional iterators}
223
/*! \fn bool qEqual(InputIterator1 begin1, InputIterator1 end1, InputIterator2 begin2)
224
\relates <QtAlgorithms>
226
Compares the items in the range [\a begin1, \a end1) with the
227
items in the range [\a begin2, ...). Returns true if all the
228
items compare equal; otherwise returns false.
231
\snippet doc/src/snippets/code/doc_src_qalgorithms.qdoc 6
233
This function requires the item type (in the example above,
234
QString) to implement \c operator==().
236
\sa {input iterators}
239
/*! \fn void qFill(ForwardIterator begin, ForwardIterator end, const T &value)
240
\relates <QtAlgorithms>
242
Fills the range [\a begin, \a end) with \a value.
245
\snippet doc/src/snippets/code/doc_src_qalgorithms.qdoc 7
247
\sa qCopy(), {forward iterators}
250
/*! \fn void qFill(Container &container, const T &value)
251
\relates <QtAlgorithms>
255
This is the same as qFill(\a{container}.begin(), \a{container}.end(), \a value);
258
/*! \fn InputIterator qFind(InputIterator begin, InputIterator end, const T &value)
259
\relates <QtAlgorithms>
261
Returns an iterator to the first occurrence of \a value in a
262
container in the range [\a begin, \a end). Returns \a end if \a
266
\snippet doc/src/snippets/code/doc_src_qalgorithms.qdoc 8
268
This function requires the item type (in the example above,
269
QString) to implement \c operator==().
271
If the items in the range are in ascending order, you can get
272
faster results by using qLowerBound() or qBinaryFind() instead of
275
\sa qBinaryFind(), {input iterators}
278
/*! \fn void qFind(const Container &container, const T &value)
279
\relates <QtAlgorithms>
283
This is the same as qFind(\a{container}.begin(), \a{container}.end(), value);
286
/*! \fn void qCount(InputIterator begin, InputIterator end, const T &value, Size &n)
287
\relates <QtAlgorithms>
289
Returns the number of occurrences of \a value in the range [\a begin, \a end),
290
which is returned in \a n. \a n is never initialized, the count is added to \a n.
291
It is the caller's responsibility to initialize \a n.
295
\snippet doc/src/snippets/code/doc_src_qalgorithms.qdoc 9
297
This function requires the item type (in the example above,
298
\c int) to implement \c operator==().
300
\sa {input iterators}
303
/*! \fn void qCount(const Container &container, const T &value, Size &n)
304
\relates <QtAlgorithms>
308
Instead of operating on iterators, as in the other overload, this function
309
operates on the specified \a container to obtain the number of instances
310
of \a value in the variable passed as a reference in argument \a n.
313
/*! \fn void qSwap(T &var1, T &var2)
314
\relates <QtAlgorithms>
316
Exchanges the values of variables \a var1 and \a var2.
319
\snippet doc/src/snippets/code/doc_src_qalgorithms.qdoc 10
322
/*! \fn void qSort(RandomAccessIterator begin, RandomAccessIterator end)
323
\relates <QtAlgorithms>
325
Sorts the items in range [\a begin, \a end) in ascending order
326
using the quicksort algorithm.
329
\snippet doc/src/snippets/code/doc_src_qalgorithms.qdoc 11
331
The sort algorithm is efficient on large data sets. It operates
332
in \l {linear-logarithmic time}, O(\e{n} log \e{n}).
334
This function requires the item type (in the example above,
335
\c{int}) to implement \c operator<().
337
If neither of the two items is "less than" the other, the items are
338
taken to be equal. It is then undefined which one of the two
339
items will appear before the other after the sort.
341
\sa qStableSort(), {random access iterators}
344
/*! \fn void qSort(RandomAccessIterator begin, RandomAccessIterator end, LessThan lessThan)
345
\relates <QtAlgorithms>
349
Uses the \a lessThan function instead of \c operator<() to
352
For example, here's how to sort the strings in a QStringList
353
in case-insensitive alphabetical order:
355
\snippet doc/src/snippets/code/doc_src_qalgorithms.qdoc 12
357
To sort values in reverse order, pass
358
\l{qGreater()}{qGreater<T>()} as the \a lessThan parameter. For
361
\snippet doc/src/snippets/code/doc_src_qalgorithms.qdoc 13
363
If neither of the two items is "less than" the other, the items are
364
taken to be equal. It is then undefined which one of the two
365
items will appear before the other after the sort.
367
An alternative to using qSort() is to put the items to sort in a
368
QMap, using the sort key as the QMap key. This is often more
369
convenient than defining a \a lessThan function. For example, the
370
following code shows how to sort a list of strings case
371
insensitively using QMap:
373
\snippet doc/src/snippets/code/doc_src_qalgorithms.qdoc 14
378
/*! \fn void qSort(Container &container)
379
\relates <QtAlgorithms>
383
This is the same as qSort(\a{container}.begin(), \a{container}.end());
387
\fn void qStableSort(RandomAccessIterator begin, RandomAccessIterator end)
388
\relates <QtAlgorithms>
390
Sorts the items in range [\a begin, \a end) in ascending order
391
using a stable sorting algorithm.
393
If neither of the two items is "less than" the other, the items are
394
taken to be equal. The item that appeared before the other in the
395
original container will still appear first after the sort. This
396
property is often useful when sorting user-visible data.
399
\snippet doc/src/snippets/code/doc_src_qalgorithms.qdoc 15
401
The sort algorithm is efficient on large data sets. It operates
402
in \l {linear-logarithmic time}, O(\e{n} log \e{n}).
404
This function requires the item type (in the example above,
405
\c{int}) to implement \c operator<().
407
\sa qSort(), {random access iterators}
411
\fn void qStableSort(RandomAccessIterator begin, RandomAccessIterator end, LessThan lessThan)
412
\relates <QtAlgorithms>
416
Uses the \a lessThan function instead of \c operator<() to
419
For example, here's how to sort the strings in a QStringList
420
in case-insensitive alphabetical order:
422
\snippet doc/src/snippets/code/doc_src_qalgorithms.qdoc 16
424
Note that earlier versions of Qt allowed using a lessThan function that took its
425
arguments by non-const reference. From 4.3 and on this is no longer possible,
426
the arguments has to be passed by const reference or value.
428
To sort values in reverse order, pass
429
\l{qGreater()}{qGreater<T>()} as the \a lessThan parameter. For
432
\snippet doc/src/snippets/code/doc_src_qalgorithms.qdoc 17
434
If neither of the two items is "less than" the other, the items are
435
taken to be equal. The item that appeared before the other in the
436
original container will still appear first after the sort. This
437
property is often useful when sorting user-visible data.
441
\fn void qStableSort(Container &container)
442
\relates <QtAlgorithms>
446
This is the same as qStableSort(\a{container}.begin(), \a{container}.end());
449
/*! \fn RandomAccessIterator qLowerBound(RandomAccessIterator begin, RandomAccessIterator end, const T &value)
450
\relates <QtAlgorithms>
452
Performs a binary search of the range [\a begin, \a end) and
453
returns the position of the first ocurrence of \a value. If no
454
such item is found, returns the position where it should be
457
The items in the range [\a begin, \e end) must be sorted in
458
ascending order; see qSort().
461
\snippet doc/src/snippets/code/doc_src_qalgorithms.qdoc 18
463
This function requires the item type (in the example above,
464
\c{int}) to implement \c operator<().
466
qLowerBound() can be used in conjunction with qUpperBound() to
467
iterate over all occurrences of the same value:
469
\snippet doc/src/snippets/code/doc_src_qalgorithms.qdoc 19
471
\sa qUpperBound(), qBinaryFind()
475
\fn RandomAccessIterator qLowerBound(RandomAccessIterator begin, RandomAccessIterator end, const T &value, LessThan lessThan)
476
\relates <QtAlgorithms>
480
Uses the \a lessThan function instead of \c operator<() to
483
Note that the items in the range must be sorted according to the order
484
specified by the \a lessThan object.
488
\fn void qLowerBound(const Container &container, const T &value)
489
\relates <QtAlgorithms>
493
For read-only iteration over containers, this function is broadly equivalent to
494
qLowerBound(\a{container}.begin(), \a{container}.end(), value). However, since it
495
returns a const iterator, you cannot use it to modify the container; for example,
499
/*! \fn RandomAccessIterator qUpperBound(RandomAccessIterator begin, RandomAccessIterator end, const T &value)
500
\relates <QtAlgorithms>
502
Performs a binary search of the range [\a begin, \a end) and
503
returns the position of the one-past-the-last occurrence of \a
504
value. If no such item is found, returns the position where the
505
item should be inserted.
507
The items in the range [\a begin, \e end) must be sorted in
508
ascending order; see qSort().
511
\snippet doc/src/snippets/code/doc_src_qalgorithms.qdoc 20
513
This function requires the item type (in the example above,
514
\c{int}) to implement \c operator<().
516
qUpperBound() can be used in conjunction with qLowerBound() to
517
iterate over all occurrences of the same value:
519
\snippet doc/src/snippets/code/doc_src_qalgorithms.qdoc 21
521
\sa qLowerBound(), qBinaryFind()
525
\fn RandomAccessIterator qUpperBound(RandomAccessIterator begin, RandomAccessIterator end, const T &value, LessThan lessThan)
526
\relates <QtAlgorithms>
530
Uses the \a lessThan function instead of \c operator<() to
533
Note that the items in the range must be sorted according to the order
534
specified by the \a lessThan object.
538
\fn void qUpperBound(const Container &container, const T &value)
539
\relates <QtAlgorithms>
543
This is the same as qUpperBound(\a{container}.begin(), \a{container}.end(), value);
547
/*! \fn RandomAccessIterator qBinaryFind(RandomAccessIterator begin, RandomAccessIterator end, const T &value)
548
\relates <QtAlgorithms>
550
Performs a binary search of the range [\a begin, \a end) and
551
returns the position of an occurrence of \a value. If there are
552
no occurrences of \a value, returns \a end.
554
The items in the range [\a begin, \a end) must be sorted in
555
ascending order; see qSort().
557
If there are many occurrences of the same value, any one of them
558
could be returned. Use qLowerBound() or qUpperBound() if you need
562
\snippet doc/src/snippets/code/doc_src_qalgorithms.qdoc 22
564
This function requires the item type (in the example above,
565
QString) to implement \c operator<().
567
See the \l{<QtAlgorithms>#binaryFind example}{detailed
568
description} for an example usage.
570
\sa qLowerBound(), qUpperBound(), {random access iterators}
573
/*! \fn RandomAccessIterator qBinaryFind(RandomAccessIterator begin, RandomAccessIterator end, const T &value, LessThan lessThan)
574
\relates <QtAlgorithms>
578
Uses the \a lessThan function instead of \c operator<() to
581
Note that the items in the range must be sorted according to the order
582
specified by the \a lessThan object.
586
\fn void qBinaryFind(const Container &container, const T &value)
587
\relates <QtAlgorithms>
591
This is the same as qBinaryFind(\a{container}.begin(), \a{container}.end(), value);
596
\fn void qDeleteAll(ForwardIterator begin, ForwardIterator end)
597
\relates <QtAlgorithms>
599
Deletes all the items in the range [\a begin, \a end) using the
600
C++ \c delete operator. The item type must be a pointer type (for
601
example, \c{QWidget *}).
604
\snippet doc/src/snippets/code/doc_src_qalgorithms.qdoc 23
606
Notice that qDeleteAll() doesn't remove the items from the
607
container; it merely calls \c delete on them. In the example
608
above, we call clear() on the container to remove the items.
610
This function can also be used to delete items stored in
611
associative containers, such as QMap and QHash. Only the objects
612
stored in each container will be deleted by this function; objects
613
used as keys will not be deleted.
615
\sa {forward iterators}
619
\fn void qDeleteAll(const Container &c)
620
\relates <QtAlgorithms>
624
This is the same as qDeleteAll(\a{c}.begin(), \a{c}.end()).
627
/*! \fn LessThan qLess()
628
\relates <QtAlgorithms>
630
Returns a functional object, or functor, that can be passed to qSort()
635
\snippet doc/src/snippets/code/doc_src_qalgorithms.qdoc 24
637
\sa {qGreater()}{qGreater<T>()}
640
/*! \fn LessThan qGreater()
641
\relates <QtAlgorithms>
643
Returns a functional object, or functor, that can be passed to qSort()
648
\snippet doc/src/snippets/code/doc_src_qalgorithms.qdoc 25
650
\sa {qLess()}{qLess<T>()}