1

我有一个 QVector 的 QVector。我想收集所有QVector中的所有元素,形成一个新的QVector。

目前我使用这样的代码

QVector<QVector<T> > vectors;
// ...
QVector<T> collected;
for (int i = 0; i < vectors.size(); ++i) {
     collected += vectors[i];
}

但似乎operator+=实际上是将每个元素附加到QVector. 那么是否有更省时的使用QVector或更合适的类型 replace QVector

4

3 回答 3

2

If you really need to, then I would do something like:

QVector< QVector<T> > vectors = QVector< QVector<T> >();

int totalSize = 0;
for (int i = 0; i < vectors.size(); ++i)
    totalSize += vectors.at(i).size();

QVector<T> collected;
collected.reserve(totalSize);

for (int i = 0; i < vectors.size(); ++i)
    collected << vectors[i];

But please take note that this sounds a bit like premature optimisation. As the documentation points out:

QVector tries to reduce the number of reallocations by preallocating up to twice as much memory as the actual data needs.

So don't do this kind of thing unless you're really sure it will improve your performance. Keep it simple (like your current way of doing it).

Edit in response to your additional requirement of O(1): Well if you're randomly inserting it's a linked list but if you're just appending (as that's all you've mentioned) you've already got amortized O(1) with the QVector. Take a look at the documentation for Qt containers.

于 2012-02-27T08:49:17.873 回答
0
for (int i = 0; i < vectors.size(); ++i) {
    for(int k=0;k<vectors[i].size();k++){
        collected.push_back(vectors[i][k]);
    }
}

外循环:从向量中取出每个向量
内循环:取出第 i 个向量中的每个元素并推入收集

于 2012-02-27T08:37:43.260 回答
0

您可以使用Boost Multi-Array,这提供了一个多维数组。

它也是一个“仅标头”库,因此您无需单独编译库,只需将标头放入项目中的文件夹并包含它们即可。

请参阅教程和示例的链接。

于 2012-02-27T10:12:19.400 回答