Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

QMap swap key and value



  • I've got this bit of code which basically reverses the key and value in a QMap:

            QMap<QString, int> modulePri = host->mModulePriorities;
            QMapIterator<QString, int> modulePriosIterator(modulePri);
            QMap<int, QStringList> moduleOrder;
            while (modulePriosIterator.hasNext()) {
                modulePriosIterator.next();
                // setup the map to be in format of priority:name
                moduleOrder[modulePriosIterator.value()].append(modulePriosIterator.key());
            }
            QMapIterator<int, QStringList> it4(moduleOrder);
            while (it4.hasNext()) {
                it4.next();
                QStringList moduleList = it4.value();
                for (int i = 0; i < moduleList.size(); i++) {
                    QString moduleName = moduleList[i];
                    if (mModulesToSync.contains(moduleName)) {
                        host->reloadModule(moduleName);
                    }
                }
            }
    

    Is there a way to write it shorter in Qt 5.7 + C++14?


  • Lifetime Qt Champion

    Hi,

    QMap<QString, int> modulePri;
    modulePri["one"] = 1;
    modulePri["two"] = 2;
    QMap<int, QStringList> moduleOrder;
    
    // Qt 5.7
    for (auto it = modulePri.keyBegin() ; it != modulePri.keyEnd() ; ++it) {
        moduleOrder[modulePri[*it]].append(*it);
    }
    
    // Qt 5.10
    for (auto it = modulePri.constKeyValueBegin() ; it != modulePri.constKeyValueEnd() ; ++it) {
        moduleOrder[(*it).second].append((*it).first);
    }
    


  • Thanks a ton!


Log in to reply