Domanda

This shows how to access the pointer to the raw data in std::vector. I want something like that in Qt for QVector, QQueue and QList (If possible other containers).

For instance if we have some containers:

QVector<int> vector;
QQueue<int> queue;
QList<int> list;

And these pointers:

int * p1 = &vector[0];
int * p2 = &queue[0];
int * p3 = &list[0];

Do the above pointers point to raw data in containers?

For the above case i made a test. The code is:

QVector<int> vector;
QQueue<int> queue;
QList<int> list;

for(int i=0;i<10;i++)
{
    vector.append(i);
    queue.enqueue(i);
    list.append(i);
}

int * P1 = &vector[0];
int * P2 = &queue[0];
int * P3 = &list[0];

for(int i=0;i<10;i++)
    qDebug()<<P1[i]<<P2[i]<<P3[i]<<"\n";

And the result is:

0 0 0

1 1 1

2 2 2

3 3 3

4 4 4

5 5 5

6 6 6

7 7 7

8 8 8

9 9 9

So at least it is true for the case of int type.

But the same test with double type failed. Just QVector elements were correct for type double.

Is it possible to get pointer to raw data in QQueue and QList?

È stato utile?

Soluzione

This does not seem like a good idea and might fail with a segmentation fault at some random point in the future. The reason that QList and QQueue don't have a data() function is that QList does not guarantee that the list items are next to each other in memory. Compare:

QVector is one of Qt's generic container classes. It stores its items in adjacent memory locations and provides fast index-based access.

vs.

List is one of Qt's generic container classes. It stores a list of values and provides fast index-based access as well as fast insertions and removals.

Your test indicates that it works right now, and it also seems to work with 10000 or 1000000 items. But that's an implementation detail and there's no guarantee that some future version of Qt won't change the internal workings of QList for performance or other reasons.

Also, there's a catch: Everything larger than a pointer (e.g. QList<someStruct>) will only be stored in the list as a pointer, while the actual item resides on the heap.


In fact, the Qt documentation states that QList does use arrays internally:

Internally, the QList is implemented using an array, ensuring that index-based access is very fast.

But even that wouldn't necessarily mean that all items are contiguous. One might imagine a far-fetched implementation where the list stores blocks of items, such that each block is an individual array.

Altri suggerimenti

It could be done properly using the Qt functions. For example:

QVector<int> vector;
int* ptr = vector.data();
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top