1 /****************************************************************************
3 ** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies).
4 ** Contact: http://www.qt-project.org/
6 ** This file is part of the documentation of the Qt Toolkit.
8 ** $QT_BEGIN_LICENSE:FDL$
9 ** GNU Free Documentation License
10 ** Alternatively, this file may be used under the terms of the GNU Free
11 ** Documentation License version 1.3 as published by the Free Software
12 ** Foundation and appearing in the file included in the packaging of
16 ** Alternatively, this file may be used in accordance with the terms
17 ** and conditions contained in a signed written agreement between you
26 ****************************************************************************/
29 \headerfile <QtAlgorithms>
30 \title Generic Algorithms
33 \brief The <QtAlgorithms> header includes the generic, template-based algorithms.
35 Qt provides a number of global template functions in \c
36 <QtAlgorithms> that work on containers and perform well-know
37 algorithms. You can use these algorithms with any \l {container
38 class} that provides STL-style iterators, including Qt's QList,
39 QLinkedList, QVector, QMap, and QHash classes.
41 These functions have taken their inspiration from similar
42 functions available in the STL \c <algorithm> header. Most of them
43 have a direct STL equivalent; for example, qCopyBackward() is the
44 same as STL's copy_backward() algorithm.
46 If STL is available on all your target platforms, you can use the
47 STL algorithms instead of their Qt counterparts. One reason why
48 you might want to use the STL algorithms is that STL provides
49 dozens and dozens of algorithms, whereas Qt only provides the most
50 important ones, making no attempt to duplicate functionality that
51 is already provided by the C++ standard.
53 Most algorithms take \l {STL-style iterators} as parameters. The
54 algorithms are generic in the sense that they aren't bound to a
55 specific iterator class; you can use them with any iterators that
56 meet a certain set of requirements.
58 Let's take the qFill() algorithm as an example. Unlike QVector,
59 QList has no fill() function that can be used to fill a list with
60 a particular value. If you need that functionality, you can use
63 \snippet doc/src/snippets/code/doc_src_qalgorithms.cpp 0
65 qFill() takes a begin iterator, an end iterator, and a value.
66 In the example above, we pass \c list.begin() and \c list.end()
67 as the begin and end iterators, but this doesn't have to be
70 \snippet doc/src/snippets/code/doc_src_qalgorithms.cpp 1
72 Different algorithms can have different requirements for the
73 iterators they accept. For example, qFill() accepts two
74 \l {forward iterators}. The iterator types required are specified
75 for each algorithm. If an iterator of the wrong type is passed (for
76 example, if QList::ConstIterator is passed as an \l {output
77 iterator}), you will always get a compiler error, although not
78 necessarily a very informative one.
80 Some algorithms have special requirements on the value type
81 stored in the containers. For example, qEqual() requires that the
82 value type supports operator==(), which it uses to compare items.
83 Similarly, qDeleteAll() requires that the value type is a
84 non-const pointer type (for example, QWidget *). The value type
85 requirements are specified for each algorithm, and the compiler
86 will produce an error if a requirement isn't met.
88 \target binaryFind example
90 The generic algorithms can be used on other container classes
91 than those provided by Qt and STL. The syntax of STL-style
92 iterators is modeled after C++ pointers, so it's possible to use
93 plain arrays as containers and plain pointers as iterators. A
94 common idiom is to use qBinaryFind() together with two static
95 arrays: one that contains a list of keys, and another that
96 contains a list of associated values. For example, the following
97 code will look up an HTML entity (e.g., \c &) in the \c
98 name_table array and return the corresponding Unicode value from
99 the \c value_table if the entity is recognized:
101 \snippet doc/src/snippets/code/doc_src_qalgorithms.cpp 2
103 This kind of code is for advanced users only; for most
104 applications, a QMap- or QHash-based approach would work just as
107 \snippet doc/src/snippets/code/doc_src_qalgorithms.cpp 3
109 \section1 Types of Iterators
111 The algorithms have certain requirements on the iterator types
112 they accept, and these are specified individually for each
113 function. The compiler will produce an error if a requirement
116 \section2 Input Iterators
118 An \e{input iterator} is an iterator that can be used for reading
119 data sequentially from a container. It must provide the following
120 operators: \c{==} and \c{!=} for comparing two iterators, unary
121 \c{*} for retrieving the value stored in the item, and prefix
122 \c{++} for advancing to the next item.
124 The Qt containers' iterator types (const and non-const) are all
127 \section2 Output Iterators
129 An \e{output iterator} is an iterator that can be used for
130 writing data sequentially to a container or to some output
131 stream. It must provide the following operators: unary \c{*} for
132 writing a value (i.e., \c{*it = val}) and prefix \c{++} for
133 advancing to the next item.
135 The Qt containers' non-const iterator types are all output
138 \section2 Forward Iterators
140 A \e{forward iterator} is an iterator that meets the requirements
141 of both input iterators and output iterators.
143 The Qt containers' non-const iterator types are all forward
146 \section2 Bidirectional Iterators
148 A \e{bidirectional iterator} is an iterator that meets the
149 requirements of forward iterators but that in addition supports
150 prefix \c{--} for iterating backward.
152 The Qt containers' non-const iterator types are all bidirectional
155 \section2 Random Access Iterators
157 The last category, \e{random access iterators}, is the most
158 powerful type of iterator. It supports all the requirements of a
159 bidirectional iterator, and supports the following operations:
162 \row \li \c{i += n} \li advances iterator \c i by \c n positions
163 \row \li \c{i -= n} \li moves iterator \c i back by \c n positions
164 \row \li \c{i + n} or \c{n + i} \li returns the iterator for the item \c
165 n positions ahead of iterator \c i
166 \row \li \c{i - n} \li returns the iterator for the item \c n positions behind of iterator \c i
167 \row \li \c{i - j} \li returns the number of items between iterators \c i and \c j
168 \row \li \c{i[n]} \li same as \c{*(i + n)}
169 \row \li \c{i < j} \li returns true if iterator \c j comes after iterator \c i
172 QList and QVector's non-const iterator types are random access iterators.
174 \sa {container classes}, <QtGlobal>
177 /*! \fn OutputIterator qCopy(InputIterator begin1, InputIterator end1, OutputIterator begin2)
178 \relates <QtAlgorithms>
180 Copies the items from range [\a begin1, \a end1) to range [\a
181 begin2, ...), in the order in which they appear.
183 The item at position \a begin1 is assigned to that at position \a
184 begin2; the item at position \a begin1 + 1 is assigned to that at
185 position \a begin2 + 1; and so on.
188 \snippet doc/src/snippets/code/doc_src_qalgorithms.cpp 4
190 \sa qCopyBackward(), {input iterators}, {output iterators}
193 /*! \fn BiIterator2 qCopyBackward(BiIterator1 begin1, BiIterator1 end1, BiIterator2 end2)
194 \relates <QtAlgorithms>
196 Copies the items from range [\a begin1, \a end1) to range [...,
199 The item at position \a end1 - 1 is assigned to that at position
200 \a end2 - 1; the item at position \a end1 - 2 is assigned to that
201 at position \a end2 - 2; and so on.
204 \snippet doc/src/snippets/code/doc_src_qalgorithms.cpp 5
206 \sa qCopy(), {bidirectional iterators}
209 /*! \fn bool qEqual(InputIterator1 begin1, InputIterator1 end1, InputIterator2 begin2)
210 \relates <QtAlgorithms>
212 Compares the items in the range [\a begin1, \a end1) with the
213 items in the range [\a begin2, ...). Returns true if all the
214 items compare equal; otherwise returns false.
217 \snippet doc/src/snippets/code/doc_src_qalgorithms.cpp 6
219 This function requires the item type (in the example above,
220 QString) to implement \c operator==().
222 \sa {input iterators}
225 /*! \fn void qFill(ForwardIterator begin, ForwardIterator end, const T &value)
226 \relates <QtAlgorithms>
228 Fills the range [\a begin, \a end) with \a value.
231 \snippet doc/src/snippets/code/doc_src_qalgorithms.cpp 7
233 \sa qCopy(), {forward iterators}
236 /*! \fn void qFill(Container &container, const T &value)
237 \relates <QtAlgorithms>
241 This is the same as qFill(\a{container}.begin(), \a{container}.end(), \a value);
244 /*! \fn InputIterator qFind(InputIterator begin, InputIterator end, const T &value)
245 \relates <QtAlgorithms>
247 Returns an iterator to the first occurrence of \a value in a
248 container in the range [\a begin, \a end). Returns \a end if \a
252 \snippet doc/src/snippets/code/doc_src_qalgorithms.cpp 8
254 This function requires the item type (in the example above,
255 QString) to implement \c operator==().
257 If the items in the range are in ascending order, you can get
258 faster results by using qLowerBound() or qBinaryFind() instead of
261 \sa qBinaryFind(), {input iterators}
264 /*! \fn void qFind(const Container &container, const T &value)
265 \relates <QtAlgorithms>
269 This is the same as qFind(\a{container}.constBegin(), \a{container}.constEnd(), value);
272 /*! \fn void qCount(InputIterator begin, InputIterator end, const T &value, Size &n)
273 \relates <QtAlgorithms>
275 Returns the number of occurrences of \a value in the range [\a begin, \a end),
276 which is returned in \a n. \a n is never initialized, the count is added to \a n.
277 It is the caller's responsibility to initialize \a n.
281 \snippet doc/src/snippets/code/doc_src_qalgorithms.cpp 9
283 This function requires the item type (in the example above,
284 \c int) to implement \c operator==().
286 \sa {input iterators}
289 /*! \fn void qCount(const Container &container, const T &value, Size &n)
290 \relates <QtAlgorithms>
294 Instead of operating on iterators, as in the other overload, this function
295 operates on the specified \a container to obtain the number of instances
296 of \a value in the variable passed as a reference in argument \a n.
299 /*! \fn void qSwap(T &var1, T &var2)
300 \relates <QtAlgorithms>
302 Exchanges the values of variables \a var1 and \a var2.
305 \snippet doc/src/snippets/code/doc_src_qalgorithms.cpp 10
308 /*! \fn void qSort(RandomAccessIterator begin, RandomAccessIterator end)
309 \relates <QtAlgorithms>
311 Sorts the items in range [\a begin, \a end) in ascending order
312 using the quicksort algorithm.
315 \snippet doc/src/snippets/code/doc_src_qalgorithms.cpp 11
317 The sort algorithm is efficient on large data sets. It operates
318 in \l {linear-logarithmic time}, O(\e{n} log \e{n}).
320 This function requires the item type (in the example above,
321 \c{int}) to implement \c operator<().
323 If neither of the two items is "less than" the other, the items are
324 taken to be equal. It is then undefined which one of the two
325 items will appear before the other after the sort.
327 \sa qStableSort(), {random access iterators}
330 /*! \fn void qSort(RandomAccessIterator begin, RandomAccessIterator end, LessThan lessThan)
331 \relates <QtAlgorithms>
335 Uses the \a lessThan function instead of \c operator<() to
338 For example, here's how to sort the strings in a QStringList
339 in case-insensitive alphabetical order:
341 \snippet doc/src/snippets/code/doc_src_qalgorithms.cpp 12
343 To sort values in reverse order, pass
344 \l{qGreater()}{qGreater<T>()} as the \a lessThan parameter. For
347 \snippet doc/src/snippets/code/doc_src_qalgorithms.cpp 13
349 If neither of the two items is "less than" the other, the items are
350 taken to be equal. It is then undefined which one of the two
351 items will appear before the other after the sort.
353 An alternative to using qSort() is to put the items to sort in a
354 QMap, using the sort key as the QMap key. This is often more
355 convenient than defining a \a lessThan function. For example, the
356 following code shows how to sort a list of strings case
357 insensitively using QMap:
359 \snippet doc/src/snippets/code/doc_src_qalgorithms.cpp 14
364 /*! \fn void qSort(Container &container)
365 \relates <QtAlgorithms>
369 This is the same as qSort(\a{container}.begin(), \a{container}.end());
373 \fn void qStableSort(RandomAccessIterator begin, RandomAccessIterator end)
374 \relates <QtAlgorithms>
376 Sorts the items in range [\a begin, \a end) in ascending order
377 using a stable sorting algorithm.
379 If neither of the two items is "less than" the other, the items are
380 taken to be equal. The item that appeared before the other in the
381 original container will still appear first after the sort. This
382 property is often useful when sorting user-visible data.
385 \snippet doc/src/snippets/code/doc_src_qalgorithms.cpp 15
387 The sort algorithm is efficient on large data sets. It operates
388 in \l {linear-logarithmic time}, O(\e{n} log \e{n}).
390 This function requires the item type (in the example above,
391 \c{int}) to implement \c operator<().
393 \sa qSort(), {random access iterators}
397 \fn void qStableSort(RandomAccessIterator begin, RandomAccessIterator end, LessThan lessThan)
398 \relates <QtAlgorithms>
402 Uses the \a lessThan function instead of \c operator<() to
405 For example, here's how to sort the strings in a QStringList
406 in case-insensitive alphabetical order:
408 \snippet doc/src/snippets/code/doc_src_qalgorithms.cpp 16
410 Note that earlier versions of Qt allowed using a lessThan function that took its
411 arguments by non-const reference. From 4.3 and on this is no longer possible,
412 the arguments has to be passed by const reference or value.
414 To sort values in reverse order, pass
415 \l{qGreater()}{qGreater<T>()} as the \a lessThan parameter. For
418 \snippet doc/src/snippets/code/doc_src_qalgorithms.cpp 17
420 If neither of the two items is "less than" the other, the items are
421 taken to be equal. The item that appeared before the other in the
422 original container will still appear first after the sort. This
423 property is often useful when sorting user-visible data.
427 \fn void qStableSort(Container &container)
428 \relates <QtAlgorithms>
432 This is the same as qStableSort(\a{container}.begin(), \a{container}.end());
435 /*! \fn RandomAccessIterator qLowerBound(RandomAccessIterator begin, RandomAccessIterator end, const T &value)
436 \relates <QtAlgorithms>
438 Performs a binary search of the range [\a begin, \a end) and
439 returns the position of the first ocurrence of \a value. If no
440 such item is found, returns the position where it should be
443 The items in the range [\a begin, \e end) must be sorted in
444 ascending order; see qSort().
447 \snippet doc/src/snippets/code/doc_src_qalgorithms.cpp 18
449 This function requires the item type (in the example above,
450 \c{int}) to implement \c operator<().
452 qLowerBound() can be used in conjunction with qUpperBound() to
453 iterate over all occurrences of the same value:
455 \snippet doc/src/snippets/code/doc_src_qalgorithms.cpp 19
457 \sa qUpperBound(), qBinaryFind()
461 \fn RandomAccessIterator qLowerBound(RandomAccessIterator begin, RandomAccessIterator end, const T &value, LessThan lessThan)
462 \relates <QtAlgorithms>
466 Uses the \a lessThan function instead of \c operator<() to
469 Note that the items in the range must be sorted according to the order
470 specified by the \a lessThan object.
474 \fn void qLowerBound(const Container &container, const T &value)
475 \relates <QtAlgorithms>
479 For read-only iteration over containers, this function is broadly equivalent to
480 qLowerBound(\a{container}.begin(), \a{container}.end(), value). However, since it
481 returns a const iterator, you cannot use it to modify the container; for example,
485 /*! \fn RandomAccessIterator qUpperBound(RandomAccessIterator begin, RandomAccessIterator end, const T &value)
486 \relates <QtAlgorithms>
488 Performs a binary search of the range [\a begin, \a end) and
489 returns the position of the one-past-the-last occurrence of \a
490 value. If no such item is found, returns the position where the
491 item should be inserted.
493 The items in the range [\a begin, \e end) must be sorted in
494 ascending order; see qSort().
497 \snippet doc/src/snippets/code/doc_src_qalgorithms.cpp 20
499 This function requires the item type (in the example above,
500 \c{int}) to implement \c operator<().
502 qUpperBound() can be used in conjunction with qLowerBound() to
503 iterate over all occurrences of the same value:
505 \snippet doc/src/snippets/code/doc_src_qalgorithms.cpp 21
507 \sa qLowerBound(), qBinaryFind()
511 \fn RandomAccessIterator qUpperBound(RandomAccessIterator begin, RandomAccessIterator end, const T &value, LessThan lessThan)
512 \relates <QtAlgorithms>
516 Uses the \a lessThan function instead of \c operator<() to
519 Note that the items in the range must be sorted according to the order
520 specified by the \a lessThan object.
524 \fn void qUpperBound(const Container &container, const T &value)
525 \relates <QtAlgorithms>
529 This is the same as qUpperBound(\a{container}.begin(), \a{container}.end(), value);
533 /*! \fn RandomAccessIterator qBinaryFind(RandomAccessIterator begin, RandomAccessIterator end, const T &value)
534 \relates <QtAlgorithms>
536 Performs a binary search of the range [\a begin, \a end) and
537 returns the position of an occurrence of \a value. If there are
538 no occurrences of \a value, returns \a end.
540 The items in the range [\a begin, \a end) must be sorted in
541 ascending order; see qSort().
543 If there are many occurrences of the same value, any one of them
544 could be returned. Use qLowerBound() or qUpperBound() if you need
548 \snippet doc/src/snippets/code/doc_src_qalgorithms.cpp 22
550 This function requires the item type (in the example above,
551 QString) to implement \c operator<().
553 See the \l{<QtAlgorithms>#binaryFind example}{detailed
554 description} for an example usage.
556 \sa qLowerBound(), qUpperBound(), {random access iterators}
559 /*! \fn RandomAccessIterator qBinaryFind(RandomAccessIterator begin, RandomAccessIterator end, const T &value, LessThan lessThan)
560 \relates <QtAlgorithms>
564 Uses the \a lessThan function instead of \c operator<() to
567 Note that the items in the range must be sorted according to the order
568 specified by the \a lessThan object.
572 \fn void qBinaryFind(const Container &container, const T &value)
573 \relates <QtAlgorithms>
577 This is the same as qBinaryFind(\a{container}.begin(), \a{container}.end(), value);
582 \fn void qDeleteAll(ForwardIterator begin, ForwardIterator end)
583 \relates <QtAlgorithms>
585 Deletes all the items in the range [\a begin, \a end) using the
586 C++ \c delete operator. The item type must be a pointer type (for
587 example, \c{QWidget *}).
590 \snippet doc/src/snippets/code/doc_src_qalgorithms.cpp 23
592 Notice that qDeleteAll() doesn't remove the items from the
593 container; it merely calls \c delete on them. In the example
594 above, we call clear() on the container to remove the items.
596 This function can also be used to delete items stored in
597 associative containers, such as QMap and QHash. Only the objects
598 stored in each container will be deleted by this function; objects
599 used as keys will not be deleted.
601 \sa {forward iterators}
605 \fn void qDeleteAll(const Container &c)
606 \relates <QtAlgorithms>
610 This is the same as qDeleteAll(\a{c}.begin(), \a{c}.end()).
613 /*! \fn LessThan qLess()
614 \relates <QtAlgorithms>
616 Returns a functional object, or functor, that can be passed to qSort()
621 \snippet doc/src/snippets/code/doc_src_qalgorithms.cpp 24
623 \sa {qGreater()}{qGreater<T>()}
626 /*! \fn LessThan qGreater()
627 \relates <QtAlgorithms>
629 Returns a functional object, or functor, that can be passed to qSort()
634 \snippet doc/src/snippets/code/doc_src_qalgorithms.cpp 25
636 \sa {qLess()}{qLess<T>()}