QList vs QVector revisited

后端 未结 8 2152
天涯浪人
天涯浪人 2020-12-23 22:00

My question is basically when to choose QVector and when to choose QList as your Qt container. What I already know:

  1. Qt docs: QList cl
8条回答
  •  死守一世寂寞
    2020-12-23 22:27

    Imagine, that we have DataType class.

    QVector - array of objects, such as:

    // QVector internal structure
    DataType* pArray = new DataType[100];
    

    QList - array of pointers to objects, such as:

    // QList internal structure
    DataType** pPointersArray = new DataType*[100];
    

    Therefore, direct access by index will be faster for QVector:

    {
    // ...
    cout << pArray[index]; //fast
    cout << *pPointersArray[index]; //slow, need additional operation for dereferencing
    // ...
    }
    

    But swaping will be faster for QList, if sizeof(DataType) > sizeof(DataType*):

    {
    // QVector swaping
    DataType copy = pArray[index];
    pArray[index] = pArray[index + 1];
    pArray[index + 1] = copy; // copy object
    
    // QList swaping
    DataType* pCopy = pPointersArray [index];
    pPointersArray[index] = pPointersArray [index + 1];
    pPointersArray[index + 1] = pCopy; // copy pointer
    // ...
    }
    

    So, if you need direct access without swaping operations between elements (such as sorting, for example), or sizeof(DataType) <= sizeof(DataType*), your better way is use QVector. In other case use QList.

提交回复
热议问题