Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • Users
  • Groups
  • Search
  • Get Qt Extensions
  • Unsolved
Collapse
Brand Logo
  1. Home
  2. Qt Development
  3. General and Desktop
  4. QMap swap key and value

QMap swap key and value

Scheduled Pinned Locked Moved Solved General and Desktop
3 Posts 2 Posters 960 Views
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • V Offline
    V Offline
    Vadi2
    wrote on last edited by
    #1

    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?

    1 Reply Last reply
    0
    • SGaistS Offline
      SGaistS Offline
      SGaist
      Lifetime Qt Champion
      wrote on last edited by SGaist
      #2

      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);
      }
      

      Interested in AI ? www.idiap.ch
      Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

      1 Reply Last reply
      3
      • V Offline
        V Offline
        Vadi2
        wrote on last edited by
        #3

        Thanks a ton!

        1 Reply Last reply
        0

        • Login

        • Login or register to search.
        • First post
          Last post
        0
        • Categories
        • Recent
        • Tags
        • Popular
        • Users
        • Groups
        • Search
        • Get Qt Extensions
        • Unsolved