Qt中动态数组的对比

本文对比了Qt中的QVector, QList, QLinkedList和QVarLengthArray的性能与适用场景。QVector作为默认选择,提供更好的性能;QList用于API接口;QLinkedList适合需要链表操作的场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在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 a Q_MOVABLE_TYPE or a Q_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来说,情况并非如此。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值