QVector、Qlist、QlinkedList 類 用法比較:


 QVector、Qlist、QlinkedList 類 用法比較:   

         1. QVector 是提供動態數組的一個模板類。

             QList 是提供列表的一個模板類。

             QLinkedList 是提供鏈表的一個模板類。

         2. QVector<T> 是QT的一個通用容器類,它在相鄰的內存位置中存儲items的值,並且提供基於索引(index-based)的快速訪問。

     QList<T> 是QT的一個通用容器類,它存儲列表的值,並基於索引訪問(index-based),同時,它插入和刪除元素比較快(constant time)。

             QLinkedList<T> 是QT的一個通用容器類,它存儲列表的值,並基於迭代器訪問,同時,它插入和刪除元素比較快(constant time)。

         3. QList<T>, QLinkedList<T>, QVector<T>and QVarLengthArray<T> 提供類似的功能,如下概況:

              ① 通常情況來說,QList是比較合適的選擇,QList是基於索引訪問(index-based)的API,它比QLinkedList {基於迭代器訪問(iterator-based)的API}使用更加方便。

                  由於QList在內存中存儲items的方式,它通常比QVector 更快(例如prepend()、insert()等)。而且,它只需更少的代碼。

              ② 如果你需要使用一個真正的鏈表,並且保證使用迭代器(iterator)而不是索引(index)實現快速插入(constant time),可以使用QLinkedList。

              ③ 如果你需要items占據相鄰內存空間,或者如果你的items比一個pointer更大並且你想要避免在插入時在堆上分配它們的話,可以使用QVector。

              ④ 如果你想要一個低級別的可變大小的數組,QVarLengthArray足矣。

 

 

QList和QVector等容器的區別

  1. 大多數情況下可以用QList。像prepend()insert()這種操作,通常QListQVector快的多。這是因為QList是基於index標簽存儲它的元素項在內存中,比那種依賴iterator迭代的更快捷。而且你的代碼也更少。
  2. 如果你需要一個真正的連接着的list,且需要保證一個固定插入耗時。那就用迭代器,而不是標簽。使用QLinkedList();
  3. 如果你需要開辟連續的內存空間存儲,或者你的元素遠比一個指針大,這時你需要避免個別插入操作,出現堆棧溢出,這時候用QVector
  4. 如果你需要一個低層的可變數量大小的數組,用QVarLengthArray就夠了。他可以預先在棧中分配已知長度大小的數組,如果超過這個長度,會在堆中繼續存儲。默認大小256

QVarLengthArray<int, 1024> array(n + 1);

For most purposes, QList is the right class to use. Operations like prepend() and insert() are usually faster than with QVector because of the way QList stores its items in memory (see Algorithmic Complexity for details), and its index-based API is more convenient than QLinkedList's iterator-based API. It also expands to less code in your executable.

If you need a real linked list, with guarantees of constant time insertions in the middle of the list and iterators to items rather than indexes, use QLinkedList.

If you want the items to occupy adjacent memory positions, or if your items are larger than a pointer and you want to avoid the overhead of allocating them on the heap individually at insertion time, then use QVector.

If you want a low-level variable-size array, QVarLengthArray may be sufficient.

 

看qt的文檔,只要是不要求數據所存放的內存是連續的,都建議用QList,因為QList的查詢速度跟QVecotr是差不多的。感覺有點奇怪,至少與我之前所認識的List的查詢是一不樣的。好吧,看看源碼的。
原來QList的元素的指針是通過數組來管理的,而不是用next的方式。每當插入或者刪除一個元素時,QList就會更新這個指針數組。而查詢的時候,QList只需要通過下標從此指針數組中找到元素的指針,再通過元素指針找到對應的元素即可。因此其查詢復雜度跟QVector一樣,也是常數的。只是每次查詢比QVector多了一次指針尋址而已(當然QList[idx]的調用方式還會有些不同的)。
可見QList其實不僅僅是一個鏈表,可以說是一個數組與鏈表的結合體。

再說說QVecotr,就跟我們平時理解的一回事,就是維護一個數組了的類啦。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM