Important: Please read the Qt Code of Conduct -

interesting problem with QVector

  • I'm trying to populate a 2D QVector in my app. I'd assumed that QVectors would behave as do STL vectors, but I discovered something odd.

    This builds and runs fine:

        vector <vector <int> > v;

    But this does not:

        QVector <QVector <int> > qv;

    I get a compile-time error:
    passing 'const QVector<int>' as 'this' argument discards qualifiers [-fpermissive]

    Am I doing something wrong, or is this a limitation of QVectors? Interestingly enough, if I use brackets instead of the ".at()" it also works.

  • @mzimmers :

    const T &QVector::at(int i) const
    T &QVector::operator[](int i)

    Correct me if I'm wrong, but doesn't at() deliver read-only?

  • @JNBarchan hmm, yes, you're absolutely right. That explains the compiler error.

    So, I guess I have to use the brackets? Not a problem, though I think that syntax is discouraged by the C++ purists (when using the STL).

    T &QVector::operator[](int i)
    Returns the item at index position i as a modifiable reference. (emphasis mine)

  • @mzimmers

    I'm guessing push_back() wants to modify the thing?

    And what's the declaration of the STL vector::at()? :

    QVector uses 0-based indexes, just like C++ arrays. To access the item at a particular index position, you can use operator. On non-const vectors, operator returns a reference to the item that can be used on the left side of an assignment:

    if (vector[0] == "Liz")
        vector[0] = "Elizabeth";

    For read-only access, an alternative syntax is to use at():

    for (int i = 0; i < vector.size(); ++i) {
        if ( == "Alfonso")
            cout << "Found Alfonso at position " << i << endl;

    at() can be faster than operator, because it never causes a deep copy to occur.

Log in to reply