Solved 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; v.resize(3); v.at(0).push_back(55);
But this does not:
QVector <QVector <int> > qv; qv.resize(3); qv.at(0).push_back(55);
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.
-
http://doc.qt.io/qt-5/qvector.html :
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) -
I'm guessing
push_back()
wants to modify the thing?And what's the declaration of the STL
vector::at()
?http://doc.qt.io/qt-5/qvector.html#details :
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 (vector.at(i) == "Alfonso") cout << "Found Alfonso at position " << i << endl; }
at() can be faster than operator, because it never causes a deep copy to occur.