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;
开发者_StackOverflow中文版 objOpenListStruct.parentPointId = exitPointDetailsVector[lowestWeightedPointInOpenList.pointId].exitPoint;
***********openListVector.insert (openListIterator, objOpenListStruct);
This code is under a for loop. But I have put the proper the iterator initialization, still I am getting a segmentation fault, on the starred line.
Any hints?
In the statement openListIterator <= openListVector.end()
, if you reach openListIterator == openListVector.end()
, then you're going to have a segfault, because when the code reaches openListIterator++
, your iterator becomes "out of bound"
Try openListIterator != openListVector.end()
Here is a hint. You can not use operator<= on iterators :
openListIterator <= openListVector.end()
therefore your iterator might not be good after all.
My immediate advice is: don't do that. When you want to maintain a collection of items in sorted order, you should probably use an std::set
(unless the insertion is relatively unusual). If you are going to use a sorted vector, you might as well take advantage of its being sorted and use a binary search to find the insertion point (e.g., with std::lower_bound
).
It looks like the problem you're currently experiencing is an invalid iterator when you need/want to add to the end of the collection. This (among other issues) would be handled automatically by using the pre-packaged search algorithm (or an std::set
or std::multiset
).
I wonder what could be the effect of:
&& (openListIterator <= openListVector.end()))
Indeed, in the first part of the while clause, you don't use openListIterator
, so it could well be that the loop is enteres when openListIterator
is openListVector.end()
and then it gets incremented. So, when you do the insert you get the segmentation fault...
Could you check for this condition when you have the segmentation fault?
If this is the cause of the problem, you could use instead:
&& (openListIterator < openListVector.end()))
精彩评论