Getting error when trying to access 2D QVector's elements.



  • Hello, I would like to create a matrix by using QVector. Could you tell me where I make mistake? Here is the code:

    #include <QCoreApplication>
    #include <QVector>
    #include <QDebug>
    
    int main(int argc, char* argv[]) {
        QCoreApplication a(argc, argv);
        QVector< QVector<double> > list(3);
    
        QVector<double> first(5, 1.0);
        QVector<double> second(5, 2.0);
        QVector<double> third(5, 3.0);
    
        list.append(first);
        list.append(second);
        list.append(third);
    
        qDebug() << list.at(0).at(0);
    
        return a.exec();
    }
    

    It is compiled successfully, but when I run it, it prompts a console output which says:

    ASSERT failure in QVector<T>::at: "index out of range", file ../../Qt/5.4/gcc_64/include/QtCore/qvector.h, line 388
    

    How can I solve this? If I use standard library vector class, would it solve?


  • Lifetime Qt Champion

    Hi,

    You create list with three empty elements and then you append your three other vectors. So you have in fact list size that is 6 and the first three are empty hence the assert failure.



  • @SGaist Thank you :) This solved my problem.


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.