Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pointer to QList - at() vs. [] operator

Tags:

c++

qt

qt4

qlist

I'm having problem with understanding some of QList behavior.

#include <QList>
#include <iostream>
using namespace std;

int main()
{
    QList<double> *myList;

    myList = new QList<double>;
    double myNumber;
    double ABC;

    for (int i=0; i<1000000; i++)
    {
        myNumber = i;
        myList->append(myNumber);
        ABC = myList[i]; //<----------!!!!!!!!!!!!!!!!!!!
        cout << ABC << endl;
    }

    cout << "Done!" << endl;
    return 0;
}

I get compilation error cannot convert ‘QList’ to ‘double’ in assignment at marked line. It works when I use ABC = myList.at(i), but QT reference seems to say that at() and [] operator is same thing. Does anybody know what makes the difference?

Thanks

like image 476
Moomin Avatar asked Feb 09 '10 15:02

Moomin


People also ask

How to access the data stored in a QLIST?

Another way to access the data stored in a QList is to call data (). The function returns a pointer to the first item in the list. You can use the pointer to directly access and modify the elements stored in the list. The pointer is also useful if you need to pass a QList to a function that accepts a plain C++ array.

What is the difference between QLIST and qvector in QT 6?

Unlike QVector in Qt 5, QList (and hence also QVector) in Qt 6 allows less freedom in keeping the iterators valid between operations. As a rule of thumb, consider that any operation, that adds elements to, or removes them from, the container, invalidates the "remembered" iterators, even when the QList is not implicitly shared.

What is the use of insert () function in QLIST?

Note: When QList is not implicitly shared, this function only invalidates iterators at or after the specified position. See also insert () and remove (). This is an overloaded function. Removes all the items from begin up to (but not including) end. Returns an iterator to the same item that end referred to before the call.

How to check if two lists are equal in Qt?

This function was introduced in Qt 5.14. Returns true if other is equal to this list; otherwise returns false. Two lists are considered equal if they contain the same values in the same order. This function requires the value type to have an implementation of operator== (). See also operator!= ().


2 Answers

That's because operator[] should be applied to a QList object, but myList is a pointer to QList.

Try

ABC = (*myList)[i];

instead. (Also, the correct syntax should be myList->at(i) instead of myList.at(i).)

like image 66
kennytm Avatar answered Sep 23 '22 12:09

kennytm


You've probably meant

ABC = (*myList)[i];
like image 32
Alexander Poluektov Avatar answered Sep 22 '22 12:09

Alexander Poluektov