3

I use QLists all over my code. According to https://doc.qt.io/qt-5/qvector.html and the linked page http://marcmutz.wordpress.com/effective-qt/containers/ QVector "should always be the first choice", or one shouldn't use QList at all, as long as one doesn't handle Qt API functions taking or returning a QList.

So I now think about to replace all the QLists and QStringLists in my code with QVectors (which should be no problem at all).

But what is the most efficient way to fill a QVector with data? There are three options:

QVector<sometype> vector;
for (whatever) {
    vector.append(someting)
}

This it what I currently do with most of my QLists. But often, I know how many elements the vector will have, and a QVector can be initialized with a given length or told how many elements it will have. So I can either do:

QVector<sometype> vector(count);
int i = 0;
for (whatever) {
    vector.insert(i++, something);
}

or:

QVector<sometype> vector;
vector.reserve(count);
for (whatever) {
    vector.append(something);
}

So which one is the most efficient approach?

Tobias Leupold
  • 1,512
  • 1
  • 16
  • 41
  • 1
    3 is more efficient than 1, but 2 and 3 are similar (I would guess), 3 wins on simplicity though – john Aug 03 '19 at 11:58
  • Note that 2) doesn't do what you think. It creates a `QVector` with `count` elements and then inserts further elements into that `QVector` within the loop. i.e. you probably want `vector[i] = something` rather than `vector.insert(i++, something)`. – G.M. Aug 03 '19 at 12:07
  • 1
    [std::fill](https://en.cppreference.com/w/cpp/algorithm/fill) exist and makes it quite clear what you are doing and is quite efficient. – Jesper Juhl Aug 03 '19 at 12:16
  • "void QVector::insert(int i, const T &value) Inserts value at index position i in the vector." So I think it does what I think, it replaces the default constructed values with the real ones, doesn't it? – Tobias Leupold Aug 03 '19 at 12:24

0 Answers0