在Qt的官方文档上对几种动态数组做了对比介绍。
The QVector class is a template class that provides a dynamic array.
QVector<T> is one of Qt's generic container classes. It stores its items in adjacent memory locations and provides fast index-based access.
QList<T>, QLinkedList<T>, QVector<T>, and QVarLengthArray<T> provide similar APIs and functionality. They are often interchangeable, but there are performance consequences. Here is an overview of use cases:
- QVector should be your default first choice. QVector<T> will usually give better performance than QList<T>, because QVector<T> always stores its items sequentially in memory, where QList<T> will allocate its items on the heap unless
sizeof(T) <= sizeof(void*)
and T has been declared to be either aQ_MOVABLE_TYPE
or aQ_PRIMITIVE_TYPE
using Q_DECLARE_TYPEINFO. See the Pros and Cons of Using QList for an explanation. - However, QList is used throughout the Qt APIs for passing parameters and for returning values. Use QList to interface with those APIs.
- If you need a real linked list, which guarantees constant time insertions mid-list and uses iterators to items rather than indexes, use QLinkedList.
Note: QVector and QVarLengthArray both guarantee C-compatible array layout. QList does not. This might be important if your application must interface with a C API.
Note: Iterators into a QLinkedList and references into heap-allocating QLists remain valid as long as the referenced items remain in the container. This is not true for iterators and references into a QVector and non-heap-allocating QLists.
翻译:QVector类是一个提供动态数组功能的模板类。
QVector<T>是Qt的通用容器类之一。它在相邻的内存位置上保存元素并提供基于index的快速访问。
QList<T>, QLinkedList<T>, QVector<T>, and QVarLengthArray<T> 提供类似的APIs和功能。它们通常可以互换,但是性能不同。下面是用法的概述:
- 大多数情况下QVector 应该是你的首选。 QVector<T> 通常会比QList<T>提供更好的性能,因为QVector<T> 总是在内存中按照顺序存储元素,而QList<T>会在堆上存储元素除非
sizeof(T) <= sizeof(void*)并且T已经用
Q_DECLARE_TYPEINFO被声明为
Q_MOVABLE_TYPE
或Q_PRIMITIVE_TYPE。
然而,
QList在Qt API中用于传递参数和返回值。这些API接口使用
QList。
如果你需要一个真正的链表,它能够保证在列表中间插入花费的时间是常量,使用迭代器而不是index,那么使用
QLinkedList.
注意:QVector和QVarLengthArray都保证了C语言的数组兼容。 QList没有。 如果您的应用程序必须与C API接口,这可能很重要。
注意:只要引用的项保留在容器中,QLinkedList的迭代器和堆分配QLists的引用仍然有效。 对QVector和非堆分配QLists来说,情况并非如此。