Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

For Loop Misbehavior in C++ and Qt 6.2

First of all i’m a complete beginner in C++ and Qt and i’m using Qt 6.2 and C++11. This is the code that i have problem with:

QSet<QList<QString>> listSet;
for(int i = 0; i < 10; i++)
{
    QList<QString> myList;
    for(int r = 0; r < 10; r++)
    {
        myList << "Item" + QString::number(r);
    }
    listSet.insert(myList);
}

qInfo() << listSet.count();

I was expecting that i would get the output of "10" but instead i got "1". I changed the code to this and it fixed the problem but i just can’t wrap my head around it:

QSet<QList<QString>> listSet;
for(int i = 0; i < 10; i++)
{
    QList<QString> myList;
    myList << "default" + QString::number(i);
    for(int r = 0; r < 10; r++)
    {
        myList << "Item" + QString::number(r);
    }
    listSet.insert(myList);
}

qInfo() << listSet.count();

i want to know why C++ is behaving like this.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

QSet is a collection of unique objects. The first code snipped produces 10 equal to each other myList objects. Thus, QSet gets only one unique myList object: qInfo() << listSet.count(); outputs 1.

The second snippet makes not equal myList objects, they differ by the first list items, and qInfo() << listSet.count(); outputs 10.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading