Search code examples
qtqmap

How to reverse the order of the same keys when inserted using insertMulti in QMAP?


I have a QMAP data structure. Now, I want to insert the QVariant type in the QMAP. The data is inserted based on the priority. For example priority 1, 2.. etc. These priority is the key in the QMAP. However, I can have the same key values - meaning same priority. This means priority 1, and 1 can have different QVariants. In order to suffice this, I am using insertMulti rather than insert. Now, the difficulty is that the last insertMulti having the same key is getting inserted on the top of the previously insert value. Now, how can I make it reverse?

QMAP<int, QVariant> grp;

grp.insertMulti(0, "HELLO");
grp.insetMulti(0. "Hi");

On reading the values -

It first returs Hi. However, I want it to return HeLLO. How can I do so? Please don't give answers in using other data structures. This is a snippet of a very complex problem.


Solution

  • Problem - If the multiple keys are stored in the same key, then the last value added for the same key will have a preference. As per the document - Returns a list containing all the values associated with key key, from the most recently inserted to the least recently inserted one.

    Solution - To get it back to the same form - again traverse the QMAP and insert it in the other QMAP. Now, the values associated with the same key will be reversed again - based on the fundamental that recently accessed will be at the top for the same key value.

    QMAP<int, QVariant> grp;
    
    grp.insertMulti(0, "HELLO");
    grp.insetMulti(0. "Hi");
    

    solution

    QMAP<int, QVariant> pgrp;
    
    QMap<int, QVariant>::const_iterator pGroupServiceIterator = grp.constBegin();
    
    while (pGroupServiceIterator != grp.constEnd())
                {
                       pgrp.insertMulti(pGroupServiceIterator.key(),pGroupServiceIterator.value());
    
                   ++pGroupServiceIterator;
                }
    

    Now, the print you will get is "HELLO" first rather than Hi when the pgrp is traversed and printed.