When using QMap to save data, if the same key appears, you can use the insertMulti function to solve it without changing the original variable storage selection.

Problem scene

Originally, QMap was selected in the project selection to store the corresponding key-value pairs, and the corresponding values ​​were retrieved according to the order of the keys in the Map. However, in the process of using it, it is found that the same key will be stored in the map, so the value corresponding to this key will be overwritten, resulting in a final lack of a set of data.

Solution

For the above problems, I don't want to change too much code here, so I will screen the optimal solution.

Option One

Use QSet. Although it solves the problem that the same key can be stored, it also introduces a new problem, that is, although QSet is a key-value pair, but in daily use, only the value is stored, like this QSet<double>, cannot be directly Achieve the effect of QMap<double, QWidget*>.

Option II

Use QMultiMap. Changing the type of stored data from QMap directly to QMultiMap looks like there are very few codes that need to be modified. It seems that the original code only needs to change QMap to QMultiMap. But after I changed to QMultiMap, I found that when compiling a variable of type QMultiMap using [], an error will be reported. It is said that the private member variable [] cannot be accessed. Therefore, I did not adopt this plan.

Option Three (Key Points)

Use the original variable selection QMap, but before storing the key-value pair in the QMap, first determine whether the value of the same key is already stored in the QMap.
If the key already exists in the QMap, use the function inertMulti(). This function can save the same key in QMap.

Example for Scenario Three

Below is a simple little example.

// QMap型变量的声明如下
QMap<double, QWidget *> m_lesionMap;

void ClassWgt::saveLessionWidgetKeyIndex(const double &dKeyIndex,
                                           QWidget *pWidget)
{
    
    
    bool ret = mapIsAlreadyHasSameKeyLession(dKeyIndex);
    if (ret) //相同的键采用insertMulti函数来保存到QMap中
    {
    
    
        m_lesionMap.insertMulti(dKeyIndex, pWidget);
    }
    else
    {
    
    
        m_lesionMap[dKeyIndex] = pWidget;
    }
}

bool ClassWgt::mapIsAlreadyHasSameKeyLession(const double &dKeyIndex)
{
    
    
    auto it = m_lesionMap.find(dKeyIndex);
    while (it != m_lesionMap.end())
    {
    
    
        return true;
    }
    return false;
}

Guess you like

Origin blog.csdn.net/blqzj214817/article/details/130013433