c++ - 如何获取指向 Qt 容器中原始数据的指针?

标签 c++ qt pointers containers

This演示如何访问 std::vector 中原始数据的指针。我想要在 Qt 中为 QVector、QQueue 和 QList 提供类似的东西(如果可能的话其他容器)。

例如,如果我们有一些容器:

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

还有这些指针:

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

上面的指针是否指向容器中的原始数据?

针对上述情况我做了一个测试。代码是:

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";

结果是:

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

所以至少对于 int 类型来说是这样。

但是使用 double 类型进行相同的测试失败了。对于 double 类型,只有 QVector 元素是正确的。

是否可以获取指向QQueue和QList中原始数据的指针?

最佳答案

这似乎不是一个好主意,并且可能会在未来的某个随机点因段错误而失败。 QList和QQueue没有data()的原因功能在于 QList 不保证列表项在内存中彼此相邻。比较:

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

对比

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.

您的测试表明它现在可以工作,并且似乎也可以处理 10000 或 1000000 个项目。但这是一个实现细节,并不能保证 Qt 的某些 future 版本不会因为性能或其他原因而改变 QList 的内部工作方式。

此外,还有一个问题:大于指针的所有内容(例如 QList<someStruct> )只会作为指针存储在列表中,而实际项目驻留在堆上。


事实上,Qt 文档指出 QList 确实在内部使用数组:

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

但即使如此也不一定意味着所有项目都是连续的。人们可能会想象一种牵强的实现,其中列表存储项目 block ,这样每个 block 都是一个单独的数组。

关于c++ - 如何获取指向 Qt 容器中原始数据的指针?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22472448/

相关文章:

c++ - 在将几行 ruby​​ 代码转换为 C++ 时需要帮助!

arrays - C++ 新手 - 无法获取指向数组的指针来工作

pointers - 为什么 http.Request 参数必须是一个指针?

Qt - 如何在顶部而不是底部显示 tabified dockwidget 的选项卡

c++ - D3D11_BUFFER_DESC字节宽度 "not working"

python - 如何在 C++ 中进行 Python 风格的字符串切片

c++ - "Vector subscript out of range",在返回语句?

c++ - 如何捕捉 QSystemTrayIcon 的 MouseHover 事件?

c - 这些代码行怎么会导致完全相同的程序有时崩溃但其他程序运行良好?

c++ - 如何在不打开 code::blocks 的情况下运行 C++ 程序?