[英]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++
,迭代器將變得“ 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()
時openListIterator
循環,然后循環遞增。 因此,當您執行插入操作時,您會遇到細分錯誤...
遇到細分錯誤時,可以檢查這種情況嗎?
如果這是導致問題的原因,則可以改用:
&& (openListIterator < openListVector.end()))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.