Как перебирать и вставлять элементы в Qmap?

У меня есть Qmap, содержит некоторые объекты (это не бесплатно), для простоты представьте, что я хочу добавить дочерний элемент каждого объекта в Qmap, поэтому мне нужно выполнить итерацию Qmap и вставить в него дочерний элемент каждого объекта. Как я могу это сделать? Однако реальный код, который немного сложнее, находится здесь:

// This parameterSearchList will be looped over to include the the parameters that are implicitly used in the function in the lists of function.
// This includes both parameter QProperties of random variables and decision variables and the parameters upstream.
// The type of the parameter is determined by down-casting a pointer of the types RRandomVariable, RDecisionVariable, RConstant and RResponse to the parameter, respectively.
// If the down-casting to -for example- RRandomVariable does not return a NULL pointer, then the type of this parameter is a random variable. Thus, the pointer is added to the list of random variables.
// Likewise, if the type of the parameter is determined to be RDecisionVarible, RConstant, or RResponse, again the pointer is added to the corresponding lists, which are theDecisionVariableList, theConstantList, and theResponseList.
QMap<QString,RParameter *> parameterSearchList = theExplicitParameterList;
int counter = 0;
QMap<QString, RParameter *>::iterator iter;
for (iter=parameterSearchList.begin(); iter != parameterSearchList.end(); ++iter) {
    if (counter++ % 100 == 0) {
        QCoreApplication::processEvents();
    }

    RParameter *parameterObject = iter.value();

    // adding a lock for the parameter if it has not been added before
    if (! theDependencyCalculationLockHash.contains(parameterObject))
        theDependencyCalculationLockHash.insert(parameterObject, new QReadWriteLock());

    // Down-casting a pointer with the type RRandomVariable to the parameter
    RRandomVariable *randomVariableObject = qobject_cast<RRandomVariable *>(parameterObject);
    // If the pointer is not NULL, then the type of the parameter is random variable. Thus, this parameter should be added to the list of random variables.
    if (randomVariableObject) {
        // If "theRandomVariableList" does not already contain this parameter ... 
        if (!theRandomVariableList.contains(randomVariableObject)) {
            // Adding the parameter to the "theRandomVariableList"
            theRandomVariableList.append(randomVariableObject);

            // Adding the parameter QProperties of the random variable to the parameterSearchList
            QList<RParameter *> tempParameterList = randomVariableObject->getParameterList();
            for (int j = 0; j < tempParameterList.count(); j++) {
                if (!parameterSearchList.contains(tempParameterList[j]->objectName())) {
                    parameterSearchList.insert(tempParameterList[j]->objectName(),tempParameterList[j]);
                }
            }
        }
        continue;
    }

    // Down-casting a pointer with the type RDecisionVariable to the parameter
    RDecisionVariable *decisionVariableObject = qobject_cast<RDecisionVariable *>(parameterObject);
    // If the pointer is not NULL, then the type of the parameter is decision variable. Thus, this parameter should be added to the list of decision variables.
    if (decisionVariableObject) {
        // If "theDecisionVariableList" does not already contain this parameter ... 
        if (!theDecisionVariableList.contains(decisionVariableObject)) {
            // Adding the parameter to the "theDecisionVariableList"
            theDecisionVariableList.append(decisionVariableObject);

            // Adding the parameter QProperties of the decision variable to the parameterSearchList
            QList<RParameter *> tempParameterList = decisionVariableObject->getParameterList();
            for (int j = 0; j < tempParameterList.count(); j++) {
                if (!parameterSearchList.contains(tempParameterList[j]->objectName())) {
                    parameterSearchList.insert(tempParameterList[j]->objectName(), tempParameterList[j]);
                }
            }
        }
        continue;
    }

    // Down-casting a pointer with the type RConstant to the parameter
    RConstant *constantObject = qobject_cast<RConstant *>(parameterObject);
    // If the pointer is not NULL, then the type of the parameter is constant. Thus, this parameter should be added to the list of constants.
    if (constantObject) {
        // If "theConstantList" does not already contain this parameter ... 
        if (!theConstantList.contains(constantObject)) {
            // Adding the parameter to the "theConstantList"
            theConstantList.append(constantObject);
        }
        continue;
    }
}

person hosh0425    schedule 02.06.2019    source источник
comment
Не могли бы вы упростить свой вопрос относительно вашего кода: какие objects вы бы добавили своих детей, к которымQMap в вашем коде.   -  person Tom Kim    schedule 02.06.2019
comment
В theExplicitParameterList есть несколько objects, я копирую их на новую карту под названием parameterSearchList. Теперь я хочу повторить это и добавить детей objects в parameterSearchList к parameterSearchList! Как вы знаете, проблема в том, что некоторые дочерние элементы могут быть добавлены перед итератором, поэтому итератор не может их видеть, и я не могу найти их дочерние элементы (это похоже на рекурсивную итерацию, до этого я использовал Qlist, и поскольку новые дочерние элементы добавляются в Qlist, я смог их перебрать, а также найти их потомков)   -  person hosh0425    schedule 03.06.2019


Ответы (1)


Это то, что вы ищете:

  • Не повторяйте карту напрямую, получите и сохраните в переменной список ключей QList<String> вашего QMap и повторите этот список следующим образом:
// Get the list of maps keys
QList<QString> keys = parameterSearchList.keys();

// iterate keys
for(QString p : keys){

    // Down-casting a pointer with the type RRandomVariable to the parameter
    RRandomVariable *randomVariableObject = qobject_cast<RRandomVariable *>(parameterSearchList[p]);

    // If the pointer is not NULL, then the type of the parameter is random variable. Thus, this parameter should be added to the list of random variables.
    if (randomVariableObject) {

        // Iterate ParameterList
        for(RParameter * param : randomVariableObject->getParameterList()) {

            // Check if not already exist in parameterSearchList
            // (optional if your sure that parameters are unique)
            if(!parameterSearchList.contains(param->objectName())){

                // add param to parameterSearchList
                parameterSearchList.insert(param->objectName(), param);

            }
        }

    }
}

Надеюсь, это поможет вам.

person Tom Kim    schedule 03.06.2019
comment
Я хочу использовать QMap из-за его меньшей временной сложности .contains() по сравнению с QList . Однако я получаю копию своего QList в QMap, затем повторяю Qlist, но проверяю .contains() на QMap - person hosh0425; 04.06.2019
comment
В моем ответе contains() используется только с QMap. Итак, извините, но я не понял, что вы хотите сказать. - person Tom Kim; 04.06.2019
comment
Вы правы, я просто хочу не использовать временный QList, что кажется невозможным. - person hosh0425; 05.06.2019
comment
Я думаю, что это лучший способ сделать то, что вы хотите, но я попытаюсь подумать о другом решении. - person Tom Kim; 05.06.2019