插入一个向量
Inserting in a vector
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::set
或std::multiset
)自动处理。
我想知道会有什么影响:
&& (openListIterator <= openListVector.end()))
实际上,在while子句的第一部分中,您没有使用openListIterator
,因此很可能在openListIterator
为openListVector.end()
时进入循环,然后它被加1。因此,当你进行插入时你会得到分割错误。
当你有分割错误时,你能检查这个情况吗?
如果这是问题的原因,您可以使用:
&& (openListIterator < openListVector.end()))
相关文章:
- 给定一个向量,如何找到该向量的所有子集和的原始索引
- 为什么一个向量上的多线程操作很慢
- 将一个向量插入另一个向量的某个位置
- 将指向给定子类的指针从一个向量复制到另一个向量
- C++ STD 函数运算符:有没有一种方法可以通过函数将一个向量映射到另一个向量上?
- 将向量之间的数字放在另一个向量之间<vector>>如果两个数字的差值为 1
- 如何在不复制的情况下将一个向量移动到另一个向量中
- 使用 std::transform 将向量向量 (a) 添加到另一个向量向量 (b)
- 如何按另一个向量的方向调整一个向量?
- 将字符向量复制到另一个向量
- 制作一对共享指针并推送一个向量
- 你能把一个向量<int64>投射到一个向量<uint8>吗
- 大家好,当一个类有一个向量作为它的数据成员时,为什么它的大小总是24?
- 为什么我们需要在优先级队列声明中添加一个向量作为参数?
- 如何将所有指针从一个向量移动到另一个向量?
- 将一个向量映射到不同的对,即使向量映射到每对时是不同的?
- 生成一个类Name_class并将两种数据类型存储在一个向量中
- 使用步骤c++构建一个向量
- 如何从另一个向量中的另一个第一元素减去向量中的第一元素
- 将一个向量对放在一个无序映射与一个映射中