想象一下鐵路線。我們有一些車站和一些列車以低速行駛(紅綠燈)。這些部分可以包含電臺。我需要將這些部分拆分爲不包含電臺的部分。當列表重新分配內存時,我應該刷新list :: iterator嗎?
例如:列車從第1500米到第3500米,列車只能以40公里/小時的速度行駛。我有兩個站在2000米和3000米。在這種情況下,我需要有三個部分:1500m - 2000m,2000m-3000m和3000m-3500m。
所以我把我原來的reduspeed部分變成std :: list,amd(while())雙循環經過它並發現它是否有內部站。 如果一個人有:
- 功能分割它分成兩個部分(temp_speed_section_1和2)
- 插入這些部分
- 消除原稿reduspeed_section
- 在列表中的實際reduspeed_section之前移動所述迭代器2 (應該是存儲在temp_speed_section_1中的對象)
- 繼續使用新插入的reduspeed_section進行搜索(因爲原始段可以包含更多站)
我的代碼:
namespace split
{
/** \brief Finds reduspeed sections (left) with inner station(s) and splits them into equivalent reduspeed sections without inner stations
*
* \param const &reduspeeds_left the origial vector of reduspeeds
* \param const &stations the stations of the line
* \return &split_reduspeeds the list to hold the new split and unchanged reduspeed sections
*
*/
bool FindOverhangingReduspeedSectionsLeft(std::vector <speed_section> const &reduspeeds_left, std::vector <station> const &stations,
std::list <speed_section> &split_reduspeeds)
{
std::copy(reduspeeds_left.begin(), reduspeeds_left.end(), std::back_inserter(split_reduspeeds));
std::list<speed_section>::iterator iter_list_reduspeeds = split_reduspeeds.begin();
int items_stations = stations.size();
speed_section temp_speed_section_1;
speed_section temp_speed_section_2;
while(iter_list_reduspeeds != split_reduspeeds.end())
{
label_1:
for (int j=0; j<items_stations; j++)
{
if (iter_list_reduspeeds->its_start < stations[j].its_left_station && stations[j].its_left_station < iter_list_reduspeeds->its_end)
{
temp_speed_section_1.its_start = iter_list_reduspeeds->its_start;
temp_speed_section_1.its_end = stations[j].its_left_station;
temp_speed_section_1.its_speed = iter_list_reduspeeds->its_speed;
temp_speed_section_2.its_start = stations[j].its_left_station;
temp_speed_section_2.its_end = iter_list_reduspeeds->its_end;
temp_speed_section_2.its_speed = iter_list_reduspeeds->its_speed;
split_reduspeeds.insert(iter_list_reduspeeds, temp_speed_section_1);
split_reduspeeds.insert(iter_list_reduspeeds, temp_speed_section_2);
split_reduspeeds.erase(iter_list_reduspeeds);
/// In order to avoid the need for sorted "stations" vector/list, iterator goes to the first part of the actual reduspeed
--iter_list_reduspeeds;
--iter_list_reduspeeds;
goto label_1;
}
}
++iter_list_reduspeeds;
}
return 0;
}
所以函數查找resduspeed部分有一站,它分裂成兩個部分,將它們插入到列表中,刪除原和重新定位的迭代器。此時,迭代器指向一個speed_section對象(正確),但該對象的成員變量具有一些隨機值。 while循環比下次嘗試向列表中插入新對象時崩潰。
我嘗試過,但faild找出問題所在。是否有可能當我將新值插入列表中時,它會重新分配內存,但迭代器不能「刷新」自己,或者類似的東西?
也代替'if'與'while'和刪除'goto'。 – LogicStuff
這不是列表錯誤;它不會重新分配內存(vector _does_ reallocate memory)。_You_正在擦除一個元素,並且使特定的迭代器無效。 – MSalters