插入一个向量

Inserting in a vector

本文关键字:一个 向量 插入      更新时间:2023-10-16
    unsigned int j   = 0;
    openListIterator = openListVector.begin ();
    while (exitPointDetailsVector[lowestWeightedPointInOpenList.pointId].branchesVector[m].connectedExitPoint >= openListVector[j].pointId)
           && (openListIterator <= openListVector.end()))
    {
        // Move the iterator.
        openListIterator++;
        // Move the index.
        j++;
    }
    // Insert in the vector in the required position.
    listStruct objOpenListStruct;
    objOpenListStruct.pointId       = exitPointDetailsVector[lowestWeightedPointInOpenList.pointId].branchesVector[m].connectedExitPoint;
    objOpenListStruct.weight        = exitPointDetailsVector[lowestWeightedPointInOpenList.pointId].weight + exitPointDetailsVector[lowestWeightedPointInOpenList.pointId].branchesVector[m].distance;
    objOpenListStruct.parentPointId = exitPointDetailsVector[lowestWeightedPointInOpenList.pointId].exitPoint;
    ***********openListVector.insert (openListIterator, objOpenListStruct);

这段代码位于for循环下。但是我已经把适当的迭代器初始化,我仍然得到分割错误,在星号线上。

提示吗?

在语句openListIterator <= openListVector.end()中,如果你到达openListIterator == openListVector.end(),那么你将有一个段错误,因为当代码到达openListIterator++时,你的迭代器变得"脱界"

试试openListIterator != openListVector.end()

这里有一个提示。不能在迭代器上使用operator<=

openListIterator <= openListVector.end()

因此你的迭代器可能根本就不好。

我的直接建议是:不要那样做。当您希望按排序顺序维护一组项时,您可能应该使用std::set(除非插入相对不常见)。如果你打算使用一个排序的向量,你不妨利用它被排序的优势,使用二分查找来找到插入点(例如,使用std::lower_bound)。

看起来你当前遇到的问题是当你需要/想要添加到集合的末尾时,迭代器无效。这(以及其他问题)将通过使用预打包的搜索算法(或std::setstd::multiset)自动处理。

我想知道会有什么影响:

       && (openListIterator <= openListVector.end()))

实际上,在while子句的第一部分中,您没有使用openListIterator,因此很可能在openListIteratoropenListVector.end()时进入循环,然后它被加1。因此,当你进行插入时你会得到分割错误。

当你有分割错误时,你能检查这个情况吗?

如果这是问题的原因,您可以使用:

       && (openListIterator < openListVector.end()))