векторные итераторы несовместимы Vector Line 251

Я отлаживаю код, имеющий дело с векторами и итераторами. Я получаю ошибку подтверждения, когда нажимаю кнопку «Создать» в моем графическом интерфейсе. Ошибка утверждения заключается в том, что в заголовке добавлена ​​строка / вектор 251.

Я проследил проблему до части кода, пытающейся удалить элемент из вектора. Я опубликую всю функцию, а затем строку с ошибками:

int VsuCNTreeNodeManager::deleteTreeNode(RWCString & CNNameToDelete, RWTValSlist<VsuDeletedCN> & deletedCNList)
{
RWCString childName,  parentName;
VsuCNTreeNode *pNode;
int i;
int size;

if (!nodeList.contains(CNNameToDelete))
return 1; // Means that CNNameToDelete doest not exist.

pNode = ordCNList[nodeList[CNNameToDelete]];

travForName.reset();
travForName.processElement(pNode);

const RWTValSlist<RWCString> & childNameList = travForName.getNameList();

size = childNameList.entries();

// If it is the Top node that is deleted then
// the VsuCNTreeNodeManager's top node pointer is reset.

if ( pNode == pTopCNTreeNode )
{
pTopCNTreeNode = NULL;
}

for ( i = 0; i < size; i++)
{
//******* How would it possible to have a name not contained in the nodeList
//******* since it has been extracted from the nodeList ?????????????

childName = childNameList.at(i);

if (nodeList.contains(childName))
{
//******* Process that get the Parent List of each deleted Tree Node
//******* The following code unref all the Tree Nodes that was referencing any deleted Tree Node

pNode = ordCNList[nodeList[childName]]; // Get the Tree Node to be deleted

// Fill the deletedCNList
deletedCNList.insert( VsuDeletedCN(childName, pNode->getCN()->hasType()) );

VsuDependencyRemoverVisitor visitor( *pNode );

for (unsigned int k = 0; k < pNode->getParentList().entries(); k++)
{
parentName = pNode->getParentList().at(k)->getCN()->getName();

if ( nodeList.contains(parentName) ) // Check if the parent is not deleted
{
//*** Remove the reference of the deleted tree node from that parent
RWBoolean status;
status = ordCNList[nodeList[parentName]]->removeElem(childName); //                           Removing the reference that pNode(parent) had on key(Child)

}
}

//******* Remove references on this object from observers.

pNode->resetObserverFlags();
pNode->updateAllObservers(&visitor);

//******* Process that delete all the Tree Nodes in the parentList

nodeList.remove(childName);
}
}

//*****************update Lists********************

size = ordCNList.entries();
int index = 0;

RWTValHashDictionary<RWCString, int> tmpNodeList(rwhash);
//nodeList.clear();

RWTPtrOrderedVector<VsuCNTreeNode> nodeToDelete(childNameList.entries());

for(i = 0; i < size; i++)
{
pNode = ordCNList[index];
childName = pNode->getCN()->getName();

if (!childNameList.contains(childName))
{
tmpNodeList.insertKeyAndValue(childName, index);
index++;
}
else
{
ordCNList.remove(pNode);
typeList[pNode->getCN()->hasType()].treeNodeList.remove(pNode);

// Decrement type counter and if it reach 0 then
// the entry is removed.
if( !typeList[pNode->getCN()->hasType()].treeNodeList.entries() )
typeList.remove(pNode->getCN()->hasType());

nodeToDelete.insert(pNode);

}
}
nodeList.clear();
nodeList = tmpNodeList;ordCNList.resize(index);

if (!index)
pTopCNTreeNode = NULL;

for( unsigned int j=0; j < nodeToDelete.entries(); j++)
{
delete nodeToDelete[j];
}

return 0;
}

Теперь строка с ошибками:

      RWBoolean status;
status = ordCNList[nodeList[parentName]]->removeElem(childName);

Определение функции removeElem:

 RWBoolean VsuVE_Collection::removeElem(const RWCString & data)
{
VsuVE_Moveable *pMyObj = elementList.at(nameList[data]);

return removeElem1(pMyObj);
}

Определение removeElem1:

  RWBoolean  VsuVE_Collection::removeElem1(VsuVE_Moveable *elem)
{
if (elementList.remove(elem) == FALSE) // THE ASSERTION ERROR HAPPENS RIGHT HERE
return FALSE;

//**** Reordering the nameList
nameList.clear();
int size = elementList.entries();
for (int i = 0; i < size; i++)
{
nameList.insertKeyAndValue(elementList.at(i)->name, i);
}

return TRUE;
}

Я предполагаю, что функция removeElem пытается удалить векторный элемент, которого нет или который находится вне диапазона индекса, но я не могу понять, где именно я могу это исправить. Любая помощь приветствуется.

заранее спасибо

0

Решение

Неясно, какую именно платформу вы здесь используете (Rogue Wave?), Но я думаю, что возможно решить проблему.

Ключом к расшифровке этого утверждения является понимание того, что несовместимые итераторы средства. В целом это означает, что вы пытаетесь выполнить операцию над парой элементов, которые не относятся к одной и той же вещи. Например: (со стандартными контейнерами библиотеки)

std::vector<int> v1, v2;
for (auto it=v1.begin(); it!=v2.end(); it++) {  // <=== iterator incompatible
}

std::vector<int>::iterator it1=v1.begin();
v2.erase(v1); // <==== iterator incompatible

Если вы углубитесь в определение типов итераторов, которые у вас есть, то обнаружите, что при создании итератора он сохраняет ссылку на контейнер, из которого он был создан. Если затем выполнить операцию с двумя итераторами (как в первом случае выше), он может обнаружить, что они ссылаются на разные контейнеры и, следовательно, не совместимы. Во втором случае у вас есть операция над контейнером и итератором, и снова будет подтверждено, что итератор ссылается на этот контейнер.

В вашем случае кажется, что вы пытаетесь удалить элемент из контейнера. Фреймворк утверждает, что элемент не находится в контейнере (и фактически находится в другом). Я подозреваю, что вы удаляете элемент из неправильного контейнера.

0

Другие решения

Других решений пока нет …

По вопросам рекламы ammmcru@yandex.ru
Adblock
detector