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 QtCore module of the Qt Toolkit.
8 ** $QT_BEGIN_LICENSE:LGPL$
9 ** GNU Lesser General Public License Usage
10 ** This file may be used under the terms of the GNU Lesser General Public
11 ** License version 2.1 as published by the Free Software Foundation and
12 ** appearing in the file LICENSE.LGPL included in the packaging of this
13 ** file. Please review the following information to ensure the GNU Lesser
14 ** General Public License version 2.1 requirements will be met:
15 ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
17 ** In addition, as a special exception, Nokia gives you certain additional
18 ** rights. These rights are described in the Nokia Qt LGPL Exception
19 ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
21 ** GNU General Public License Usage
22 ** Alternatively, this file may be used under the terms of the GNU General
23 ** Public License version 3.0 as published by the Free Software Foundation
24 ** and appearing in the file LICENSE.GPL included in the packaging of this
25 ** file. Please review the following information to ensure the GNU General
26 ** Public License version 3.0 requirements will be met:
27 ** http://www.gnu.org/copyleft/gpl.html.
30 ** Alternatively, this file may be used in accordance with the terms and
31 ** conditions contained in a signed written agreement between you and Nokia.
40 ****************************************************************************/
50 static inline int alignmentThreshold()
52 // malloc on 32-bit platforms should return pointers that are 8-byte aligned or more
53 // while on 64-bit platforms they should be 16-byte aligned or more
54 return 2 * sizeof(void*);
57 const QVectorData QVectorData::shared_null = { Q_REFCOUNT_INITIALIZE_STATIC, 0, 0, false, 0 };
59 QVectorData *QVectorData::allocate(int size, int alignment)
61 return static_cast<QVectorData *>(alignment > alignmentThreshold() ? qMallocAligned(size, alignment) : ::malloc(size));
64 QVectorData *QVectorData::reallocate(QVectorData *x, int newsize, int oldsize, int alignment)
66 if (alignment > alignmentThreshold())
67 return static_cast<QVectorData *>(qReallocAligned(x, newsize, oldsize, alignment));
68 return static_cast<QVectorData *>(realloc(x, newsize));
71 void QVectorData::free(QVectorData *x, int alignment)
73 if (alignment > alignmentThreshold())
79 int QVectorData::grow(int sizeOfHeader, int size, int sizeOfT)
81 return qAllocMore(size * sizeOfT, sizeOfHeader) / sizeOfT;
86 \brief The QVector class is a template class that provides a dynamic array.
93 QVector\<T\> is one of Qt's generic \l{container classes}. It
94 stores its items in adjacent memory locations and provides fast
97 QList\<T\>, QLinkedList\<T\>, and QVarLengthArray\<T\> provide
98 similar functionality. Here's an overview:
101 \li For most purposes, QList is the right class to use. Operations
102 like prepend() and insert() are usually faster than with
103 QVector because of the way QList stores its items in memory
104 (see \l{Algorithmic Complexity} for details),
105 and its index-based API is more convenient than QLinkedList's
106 iterator-based API. It also expands to less code in your
108 \li If you need a real linked list, with guarantees of \l{constant
109 time} insertions in the middle of the list and iterators to
110 items rather than indexes, use QLinkedList.
111 \li If you want the items to occupy adjacent memory positions, or
112 if your items are larger than a pointer and you want to avoid
113 the overhead of allocating them on the heap individually at
114 insertion time, then use QVector.
115 \li If you want a low-level variable-size array, QVarLengthArray
119 Here's an example of a QVector that stores integers and a QVector
120 that stores QString values:
122 \snippet doc/src/snippets/code/src_corelib_tools_qvector.cpp 0
124 QVector stores a vector (or array) of items. Typically, vectors
125 are created with an initial size. For example, the following code
126 constructs a QVector with 200 elements:
128 \snippet doc/src/snippets/code/src_corelib_tools_qvector.cpp 1
130 The elements are automatically initialized with a
131 \l{default-constructed value}. If you want to initialize the
132 vector with a different value, pass that value as the second
133 argument to the constructor:
135 \snippet doc/src/snippets/code/src_corelib_tools_qvector.cpp 2
137 You can also call fill() at any time to fill the vector with a
140 QVector uses 0-based indexes, just like C++ arrays. To access the
141 item at a particular index position, you can use operator[](). On
142 non-const vectors, operator[]() returns a reference to the item
143 that can be used on the left side of an assignment:
145 \snippet doc/src/snippets/code/src_corelib_tools_qvector.cpp 3
147 For read-only access, an alternative syntax is to use at():
149 \snippet doc/src/snippets/code/src_corelib_tools_qvector.cpp 4
151 at() can be faster than operator[](), because it never causes a
152 \l{deep copy} to occur.
154 Another way to access the data stored in a QVector is to call
155 data(). The function returns a pointer to the first item in the
156 vector. You can use the pointer to directly access and modify the
157 elements stored in the vector. The pointer is also useful if you
158 need to pass a QVector to a function that accepts a plain C++
161 If you want to find all occurrences of a particular value in a
162 vector, use indexOf() or lastIndexOf(). The former searches
163 forward starting from a given index position, the latter searches
164 backward. Both return the index of the matching item if they found
165 one; otherwise, they return -1. For example:
167 \snippet doc/src/snippets/code/src_corelib_tools_qvector.cpp 5
169 If you simply want to check whether a vector contains a
170 particular value, use contains(). If you want to find out how
171 many times a particular value occurs in the vector, use count().
173 QVector provides these basic functions to add, move, and remove
174 items: insert(), replace(), remove(), prepend(), append(). With
175 the exception of append() and replace(), these functions can be slow
176 (\l{linear time}) for large vectors, because they require moving many
177 items in the vector by one position in memory. If you want a container
178 class that provides fast insertion/removal in the middle, use
179 QList or QLinkedList instead.
181 Unlike plain C++ arrays, QVectors can be resized at any time by
182 calling resize(). If the new size is larger than the old size,
183 QVector might need to reallocate the whole vector. QVector tries
184 to reduce the number of reallocations by preallocating up to twice
185 as much memory as the actual data needs.
187 If you know in advance approximately how many items the QVector
188 will contain, you can call reserve(), asking QVector to
189 preallocate a certain amount of memory. You can also call
190 capacity() to find out how much memory QVector actually
193 Note that using non-const operators and functions can cause
194 QVector to do a deep copy of the data. This is due to \l{implicit sharing}.
196 QVector's value type must be an \l{assignable data type}. This
197 covers most data types that are commonly used, but the compiler
198 won't let you, for example, store a QWidget as a value; instead,
199 store a QWidget *. A few functions have additional requirements;
200 for example, indexOf() and lastIndexOf() expect the value type to
201 support \c operator==(). These requirements are documented on a
204 Like the other container classes, QVector provides \l{Java-style
205 iterators} (QVectorIterator and QMutableVectorIterator) and
206 \l{STL-style iterators} (QVector::const_iterator and
207 QVector::iterator). In practice, these are rarely used, because
208 you can use indexes into the QVector.
210 In addition to QVector, Qt also provides QVarLengthArray, a very
211 low-level class with little functionality that is optimized for
214 QVector does \e not support inserting, prepending, appending or replacing
215 with references to its own values. Doing so will cause your application to
216 abort with an error message.
218 \sa QVectorIterator, QMutableVectorIterator, QList, QLinkedList
222 \fn QVector<T> QVector::mid(int pos, int length = -1) const
224 Returns a vector whose elements are copied from this vector,
225 starting at position \a pos. If \a length is -1 (the default), all
226 elements after \a pos are copied; otherwise \a length elements (or
227 all remaining elements if there are less than \a length elements)
232 /*! \fn QVector::QVector()
234 Constructs an empty vector.
239 /*! \fn QVector::QVector(int size)
241 Constructs a vector with an initial size of \a size elements.
243 The elements are initialized with a \l{default-constructed
249 /*! \fn QVector::QVector(int size, const T &value)
251 Constructs a vector with an initial size of \a size elements.
252 Each element is initialized with \a value.
257 /*! \fn QVector::QVector(const QVector<T> &other)
259 Constructs a copy of \a other.
261 This operation takes \l{constant time}, because QVector is
262 \l{implicitly shared}. This makes returning a QVector from a
263 function very fast. If a shared instance is modified, it will be
264 copied (copy-on-write), and that takes \l{linear time}.
269 /*! \fn QVector::QVector(std::initializer_list<T> args)
272 Construct a vector from the std::initilizer_list given by \a args.
274 This constructor is only enabled if the compiler supports C++0x
278 /*! \fn QVector::~QVector()
283 /*! \fn QVector<T> &QVector::operator=(const QVector<T> &other)
285 Assigns \a other to this vector and returns a reference to this
289 /*! \fn void QVector::swap(QVector<T> &other)
292 Swaps vector \a other with this vector. This operation is very fast and
296 /*! \fn bool QVector::operator==(const QVector<T> &other) const
298 Returns true if \a other is equal to this vector; otherwise
301 Two vectors are considered equal if they contain the same values
304 This function requires the value type to have an implementation
310 /*! \fn bool QVector::operator!=(const QVector<T> &other) const
312 Returns true if \a other is not equal to this vector; otherwise
315 Two vectors are considered equal if they contain the same values
318 This function requires the value type to have an implementation
324 /*! \fn int QVector::size() const
326 Returns the number of items in the vector.
328 \sa isEmpty(), resize()
331 /*! \fn bool QVector::isEmpty() const
333 Returns true if the vector has size 0; otherwise returns false.
338 /*! \fn void QVector::resize(int size)
340 Sets the size of the vector to \a size. If \a size is greater than the
341 current size, elements are added to the end; the new elements are
342 initialized with a \l{default-constructed value}. If \a size is less
343 than the current size, elements are removed from the end.
348 /*! \fn int QVector::capacity() const
350 Returns the maximum number of items that can be stored in the
351 vector without forcing a reallocation.
353 The sole purpose of this function is to provide a means of fine
354 tuning QVector's memory usage. In general, you will rarely ever
355 need to call this function. If you want to know how many items are
356 in the vector, call size().
358 \sa reserve(), squeeze()
361 /*! \fn void QVector::reserve(int size)
363 Attempts to allocate memory for at least \a size elements. If you
364 know in advance how large the vector will be, you can call this
365 function, and if you call resize() often you are likely to get
366 better performance. If \a size is an underestimate, the worst
367 that will happen is that the QVector will be a bit slower.
369 The sole purpose of this function is to provide a means of fine
370 tuning QVector's memory usage. In general, you will rarely ever
371 need to call this function. If you want to change the size of the
372 vector, call resize().
374 \sa squeeze(), capacity()
377 /*! \fn void QVector::squeeze()
379 Releases any memory not required to store the items.
381 The sole purpose of this function is to provide a means of fine
382 tuning QVector's memory usage. In general, you will rarely ever
383 need to call this function.
385 \sa reserve(), capacity()
388 /*! \fn void QVector::detach()
393 /*! \fn bool QVector::isDetached() const
398 /*! \fn void QVector::setSharable(bool sharable)
403 /*! \fn bool QVector::isSharedWith(const QVector<T> &other) const
408 /*! \fn T *QVector::data()
410 Returns a pointer to the data stored in the vector. The pointer
411 can be used to access and modify the items in the vector.
414 \snippet doc/src/snippets/code/src_corelib_tools_qvector.cpp 6
416 The pointer remains valid as long as the vector isn't
419 This function is mostly useful to pass a vector to a function
420 that accepts a plain C++ array.
422 \sa constData(), operator[]()
425 /*! \fn const T *QVector::data() const
430 /*! \fn const T *QVector::constData() const
432 Returns a const pointer to the data stored in the vector. The
433 pointer can be used to access the items in the vector.
434 The pointer remains valid as long as the vector isn't
437 This function is mostly useful to pass a vector to a function
438 that accepts a plain C++ array.
440 \sa data(), operator[]()
443 /*! \fn void QVector::clear()
445 Removes all the elements from the vector and releases the memory used by
449 /*! \fn const T &QVector::at(int i) const
451 Returns the item at index position \a i in the vector.
453 \a i must be a valid index position in the vector (i.e., 0 <= \a
456 \sa value(), operator[]()
459 /*! \fn T &QVector::operator[](int i)
461 Returns the item at index position \a i as a modifiable reference.
463 \a i must be a valid index position in the vector (i.e., 0 <= \a i
466 Note that using non-const operators can cause QVector to do a deep
472 /*! \fn const T &QVector::operator[](int i) const
480 \fn void QVector::append(const T &value)
482 Inserts \a value at the end of the vector.
485 \snippet doc/src/snippets/code/src_corelib_tools_qvector.cpp 7
487 This is the same as calling resize(size() + 1) and assigning \a
488 value to the new last element in the vector.
490 This operation is relatively fast, because QVector typically
491 allocates more memory than necessary, so it can grow without
492 reallocating the entire vector each time.
494 \sa operator<<(), prepend(), insert()
497 /*! \fn void QVector::prepend(const T &value)
499 Inserts \a value at the beginning of the vector.
502 \snippet doc/src/snippets/code/src_corelib_tools_qvector.cpp 8
504 This is the same as vector.insert(0, \a value).
506 For large vectors, this operation can be slow (\l{linear time}),
507 because it requires moving all the items in the vector by one
508 position further in memory. If you want a container class that
509 provides a fast prepend() function, use QList or QLinkedList
512 \sa append(), insert()
515 /*! \fn void QVector::insert(int i, const T &value)
517 Inserts \a value at index position \a i in the vector. If \a i is
518 0, the value is prepended to the vector. If \a i is size(), the
519 value is appended to the vector.
522 \snippet doc/src/snippets/code/src_corelib_tools_qvector.cpp 9
524 For large vectors, this operation can be slow (\l{linear time}),
525 because it requires moving all the items at indexes \a i and
526 above by one position further in memory. If you want a container
527 class that provides a fast insert() function, use QLinkedList
530 \sa append(), prepend(), remove()
533 /*! \fn void QVector::insert(int i, int count, const T &value)
537 Inserts \a count copies of \a value at index position \a i in the
541 \snippet doc/src/snippets/code/src_corelib_tools_qvector.cpp 10
544 /*! \fn QVector::iterator QVector::insert(iterator before, const T &value)
548 Inserts \a value in front of the item pointed to by the iterator
549 \a before. Returns an iterator pointing at the inserted item.
552 /*! \fn QVector::iterator QVector::insert(iterator before, int count, const T &value)
554 Inserts \a count copies of \a value in front of the item pointed to
555 by the iterator \a before. Returns an iterator pointing at the
556 first of the inserted items.
559 /*! \fn void QVector::replace(int i, const T &value)
561 Replaces the item at index position \a i with \a value.
563 \a i must be a valid index position in the vector (i.e., 0 <= \a
566 \sa operator[](), remove()
569 /*! \fn void QVector::remove(int i)
573 Removes the element at index position \a i.
575 \sa insert(), replace(), fill()
578 /*! \fn void QVector::remove(int i, int count)
582 Removes \a count elements from the middle of the vector, starting at
585 \sa insert(), replace(), fill()
588 /*! \fn QVector &QVector::fill(const T &value, int size = -1)
590 Assigns \a value to all items in the vector. If \a size is
591 different from -1 (the default), the vector is resized to size \a
595 \snippet doc/src/snippets/code/src_corelib_tools_qvector.cpp 11
600 /*! \fn int QVector::indexOf(const T &value, int from = 0) const
602 Returns the index position of the first occurrence of \a value in
603 the vector, searching forward from index position \a from.
604 Returns -1 if no item matched.
607 \snippet doc/src/snippets/code/src_corelib_tools_qvector.cpp 12
609 This function requires the value type to have an implementation of
612 \sa lastIndexOf(), contains()
615 /*! \fn int QVector::lastIndexOf(const T &value, int from = -1) const
617 Returns the index position of the last occurrence of the value \a
618 value in the vector, searching backward from index position \a
619 from. If \a from is -1 (the default), the search starts at the
620 last item. Returns -1 if no item matched.
623 \snippet doc/src/snippets/code/src_corelib_tools_qvector.cpp 13
625 This function requires the value type to have an implementation of
631 /*! \fn bool QVector::contains(const T &value) const
633 Returns true if the vector contains an occurrence of \a value;
634 otherwise returns false.
636 This function requires the value type to have an implementation of
639 \sa indexOf(), count()
642 /*! \fn bool QVector::startsWith(const T &value) const
645 Returns true if this vector is not empty and its first
646 item is equal to \a value; otherwise returns false.
648 \sa isEmpty(), first()
651 /*! \fn bool QVector::endsWith(const T &value) const
654 Returns true if this vector is not empty and its last
655 item is equal to \a value; otherwise returns false.
657 \sa isEmpty(), last()
661 /*! \fn int QVector::count(const T &value) const
663 Returns the number of occurrences of \a value in the vector.
665 This function requires the value type to have an implementation of
668 \sa contains(), indexOf()
671 /*! \fn int QVector::count() const
678 /*! \fn QVector::iterator QVector::begin()
680 Returns an \l{STL-style iterator} pointing to the first item in
683 \sa constBegin(), end()
686 /*! \fn QVector::const_iterator QVector::begin() const
691 /*! \fn QVector::const_iterator QVector::cbegin() const
694 Returns a const \l{STL-style iterator} pointing to the first item
700 /*! \fn QVector::const_iterator QVector::constBegin() const
702 Returns a const \l{STL-style iterator} pointing to the first item
705 \sa begin(), constEnd()
708 /*! \fn QVector::iterator QVector::end()
710 Returns an \l{STL-style iterator} pointing to the imaginary item
711 after the last item in the vector.
713 \sa begin(), constEnd()
716 /*! \fn QVector::const_iterator QVector::end() const
721 /*! \fn QVector::const_iterator QVector::cend() const
724 Returns a const \l{STL-style iterator} pointing to the imaginary
725 item after the last item in the vector.
730 /*! \fn QVector::const_iterator QVector::constEnd() const
732 Returns a const \l{STL-style iterator} pointing to the imaginary
733 item after the last item in the vector.
735 \sa constBegin(), end()
738 /*! \fn QVector::iterator QVector::erase(iterator pos)
740 Removes the item pointed to by the iterator \a pos from the
741 vector, and returns an iterator to the next item in the vector
742 (which may be end()).
744 \sa insert(), remove()
747 /*! \fn QVector::iterator QVector::erase(iterator begin, iterator end)
751 Removes all the items from \a begin up to (but not including) \a
752 end. Returns an iterator to the same item that \a end referred to
756 /*! \fn T& QVector::first()
758 Returns a reference to the first item in the vector. This
759 function assumes that the vector isn't empty.
761 \sa last(), isEmpty()
764 /*! \fn const T& QVector::first() const
769 /*! \fn T& QVector::last()
771 Returns a reference to the last item in the vector. This function
772 assumes that the vector isn't empty.
774 \sa first(), isEmpty()
777 /*! \fn const T& QVector::last() const
782 /*! \fn T QVector::value(int i) const
784 Returns the value at index position \a i in the vector.
786 If the index \a i is out of bounds, the function returns
787 a \l{default-constructed value}. If you are certain that
788 \a i is within bounds, you can use at() instead, which is slightly
791 \sa at(), operator[]()
794 /*! \fn T QVector::value(int i, const T &defaultValue) const
798 If the index \a i is out of bounds, the function returns
802 /*! \fn void QVector::push_back(const T &value)
804 This function is provided for STL compatibility. It is equivalent
808 /*! \fn void QVector::push_front(const T &value)
810 This function is provided for STL compatibility. It is equivalent
811 to prepend(\a value).
814 /*! \fn void QVector::pop_front()
816 This function is provided for STL compatibility. It is equivalent
820 /*! \fn void QVector::pop_back()
822 This function is provided for STL compatibility. It is equivalent
826 /*! \fn T& QVector::front()
828 This function is provided for STL compatibility. It is equivalent
832 /*! \fn QVector::const_reference QVector::front() const
837 /*! \fn QVector::reference QVector::back()
839 This function is provided for STL compatibility. It is equivalent
843 /*! \fn QVector::const_reference QVector::back() const
848 /*! \fn bool QVector::empty() const
850 This function is provided for STL compatibility. It is equivalent
851 to isEmpty(), returning true if the vector is empty; otherwise
855 /*! \fn QVector<T> &QVector::operator+=(const QVector<T> &other)
857 Appends the items of the \a other vector to this vector and
858 returns a reference to this vector.
860 \sa operator+(), append()
863 /*! \fn void QVector::operator+=(const T &value)
867 Appends \a value to the vector.
869 \sa append(), operator<<()
872 /*! \fn QVector<T> QVector::operator+(const QVector<T> &other) const
874 Returns a vector that contains all the items in this vector
875 followed by all the items in the \a other vector.
880 /*! \fn QVector<T> &QVector::operator<<(const T &value)
882 Appends \a value to the vector and returns a reference to this
885 \sa append(), operator+=()
888 /*! \fn QVector<T> &QVector::operator<<(const QVector<T> &other)
890 Appends \a other to the vector and returns a reference to the
894 /*! \typedef QVector::iterator
896 The QVector::iterator typedef provides an STL-style non-const
897 iterator for QVector and QStack.
899 QVector provides both \l{STL-style iterators} and \l{Java-style
900 iterators}. The STL-style non-const iterator is simply a typedef
901 for "T *" (pointer to T).
903 \sa QVector::begin(), QVector::end(), QVector::const_iterator, QMutableVectorIterator
906 /*! \typedef QVector::const_iterator
908 The QVector::const_iterator typedef provides an STL-style const
909 iterator for QVector and QStack.
911 QVector provides both \l{STL-style iterators} and \l{Java-style
912 iterators}. The STL-style const iterator is simply a typedef for
913 "const T *" (pointer to const T).
915 \sa QVector::constBegin(), QVector::constEnd(), QVector::iterator, QVectorIterator
918 /*! \typedef QVector::Iterator
920 Qt-style synonym for QVector::iterator.
923 /*! \typedef QVector::ConstIterator
925 Qt-style synonym for QVector::const_iterator.
928 /*! \typedef QVector::const_pointer
930 Typedef for const T *. Provided for STL compatibility.
933 /*! \typedef QVector::const_reference
935 Typedef for T &. Provided for STL compatibility.
938 /*! \typedef QVector::difference_type
940 Typedef for ptrdiff_t. Provided for STL compatibility.
943 /*! \typedef QVector::pointer
945 Typedef for T *. Provided for STL compatibility.
948 /*! \typedef QVector::reference
950 Typedef for T &. Provided for STL compatibility.
953 /*! \typedef QVector::size_type
955 Typedef for int. Provided for STL compatibility.
958 /*! \typedef QVector::value_type
960 Typedef for T. Provided for STL compatibility.
963 /*! \fn QList<T> QVector<T>::toList() const
965 Returns a QList object with the data contained in this QVector.
969 \snippet doc/src/snippets/code/src_corelib_tools_qvector.cpp 14
971 \sa fromList(), QList::fromVector()
974 /*! \fn QVector<T> QVector<T>::fromList(const QList<T> &list)
976 Returns a QVector object with the data contained in \a list.
980 \snippet doc/src/snippets/code/src_corelib_tools_qvector.cpp 15
982 \sa toList(), QList::toVector()
985 /*! \fn QVector<T> QVector<T>::fromStdVector(const std::vector<T> &vector)
987 Returns a QVector object with the data contained in \a vector. The
988 order of the elements in the QVector is the same as in \a vector.
992 \snippet doc/src/snippets/code/src_corelib_tools_qvector.cpp 16
994 \sa toStdVector(), QList::fromStdList()
997 /*! \fn std::vector<T> QVector<T>::toStdVector() const
999 Returns a std::vector object with the data contained in this QVector.
1002 \snippet doc/src/snippets/code/src_corelib_tools_qvector.cpp 17
1004 \sa fromStdVector(), QList::toStdList()
1007 /*! \fn QDataStream &operator<<(QDataStream &out, const QVector<T> &vector)
1010 Writes the vector \a vector to stream \a out.
1012 This function requires the value type to implement \c operator<<().
1014 \sa \link datastreamformat.html Format of the QDataStream operators \endlink
1017 /*! \fn QDataStream &operator>>(QDataStream &in, QVector<T> &vector)
1020 Reads a vector from stream \a in into \a vector.
1022 This function requires the value type to implement \c operator>>().
1024 \sa \link datastreamformat.html Format of the QDataStream operators \endlink