[英]Segmentation fault in std::vector::erase() in Visual C++
我在std :: vector的擦除功能中出現分段錯誤,這使我發瘋。 有以下代碼:
std::map<uint32_t, std::vector<boost::uuids::uuid> >::iterator it
= theAs.find(lSomeUint32);
if (it != theAs.end()) {
std::vector<boost::uuids::uuid>& lIds = it->second; // vector contains one entry
std::vector<boost::uuids::uuid>::iterator it2 = lIds.begin();
while (it2 != lIds.end()) {
if (*it2 == lSomeUuid) {
lIds.erase(it2);
break;
}
++it2;
}
}
在lIds.erase(it2)中,我遇到了分段錯誤。 更准確地說,我從擦除中調用了_Orphan_range(可在c:\\ Program Files \\ Microsoft Visual Studio 10.0 \\ VC \\ include \\ vector中找到)分段錯誤。 但是我不知道為什么。 向量和迭代器看起來不錯。 但是在_Orphan_range中,某些事情完全出錯了。 盡管我的向量僅包含一項,但while循環執行了3次。 在第三次運行中,變量_Pnext被破壞。
有人有主意嗎? 那將是真棒!
大衛
不幸的是(或者幸運的是),上面的示例執行了獨立的工作。 但是在我的大型軟件項目中,它不起作用。
有人知道失敗的函數_Orphan_range被執行什么嗎?
從std :: vector擦除會使迭代器無效。 請參見STL vector :: erase。因此,在第一次調用擦除之后,it2無效。 las,檢查((it2!= lIds.end())”將不成立。
將您的代碼更改為:
if (*it2 == lSomeUuid) {
it2 = lIds.erase(it2);
break;
}
您比較錯誤的end
迭代器。
std::vector<boost::uuids::uuid>::iterator it2 = lIds.begin();
while (it2 != pIds.end()) {
注意lIds
和pIds
。 嘗試在變量名稱中使用更多字母,不要使用匈牙利符號。 您幾乎立即捕獲了Ids_ptr
。
不是你的
"theAs.find(lSomeUint32);"
返回索引位置而不是Map :: iterator? 我對此不確定。 你可以看看嗎? find()函數返回lSomeUint32在theAs中的位置,並將返回該lSomeUint32在字符串中的位置(如果存在)。 我想這就是您的擦除功能引發錯誤的原因。 它不能刪除不存在的數據或不在程序范圍內的數據。
即使在其他情況下,如果您的find()返回了映射對象,除此以外,我還要放置一個簡單的if結構,以檢查該特定find()是否返回任何對象或為NULL,只是要確保在為迭代器分配一個值之前經營。
只是一個建議。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.