Question

I've got a QVector of QVector. And I want to collect all elements in all QVectors to form a new QVector.

Currently I use the code like this

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

But it seems the operator+= is actually appending each element to the QVector. So is there a more time-efficent usage of QVector or a better suitable type replace QVector?

Was it helpful?

Solution

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.

OTHER TIPS

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

outer loop: take out each vector from vectors
inner loop: take out each element in the i'th vector and push into collected

You could use Boost Multi-Array, this provides a multi-dimensional array.

It is also a 'header only' library, so you don't need to separately compile a library, just drop the headers into a folder in your project and include them.

See the link for the tutorial and example.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top