Search code examples
qt5qstringqmap

How to get second value in QMap<QString, QMap<QString, QString> >


I have structure QMap<QString, QMap<QString, QString> > *map;

Next I insert data:

map = new QMap<QString,QMap<QString, QString> >;
QMap<QString,QString> *d = new QMap<QString, QString>;
d->insert("Name","Michal");
map->insert("QLineEdit",*d);

if I try

QMapIterator<QString, QMap<QString, QString> > i(*mapa);
    while (i.hasNext()) {
        i.next();
        qDebug() << "Key: " << i.key() << " Value: " << i.value() << endl;

    }

I get:

Key:  "QLineEdit"  Value:  QMap(("Name", "Michal")).

How do I get Name as Key and Michal as Value?

I've tried:

QMap<QString, QString> *p = new QMap<QString, QString>;
  *p = i.value();
  qDebug() << "Key: " << p->key() << " Value: " << p->value();

But it does not work, I get following error:

no matching function for call to 'QMap<QString, QString>::key()' qDebug()` << "Key: " << p->key() << " Value: " << p->value();

Solution

  • In your implementation the first map contains an inner map (your variable d).

    Imagine that you have another element in the d-map, say Age. Then you would have added another element:

    d->insert("Age", "42");
    

    If you now would simply try to print the p->key() as in your attempt you can not know which of the "Age" and "Name" variables you would access, hence you need a second iterator.

    If you want to print all the keys and values of this inner map you may create a new iterator that iterates the second map and gets and prints the value:

    QMapIterator<QString, QString > i2(i.value());
    while (i2.hasNext()) {
      i2.next();
      qDebug() << "  Key: " << i2.key() << " Value: " << i2.value() << endl;
    }
    

    Alternatively you can iterate inner map in the "STL-way" with .begin() and .end() checks:

    QMap<QString, QString>::const_iterator i2;
    for (i2 = i.value().begin(); i2 != i.value().end(); ++i2){
      qDebug() << "  Key: " << i2.key() << " Value: " << i2.value();
    }