這個問題在這里已經有了答案: C 容器的迭代器失效規則 (6 個答案) 18 小時前關閉。
`
vector<int> nums;
nums.push_back(1);
nums.push_back(2);
nums.push_back(3);
vector<int> res;
res.push_back(nums.front());
vector<int>::iterator it = nums.begin();
vector<int>::iterator it2 = res.begin();
it;
cout << "it2 -> " << *it2 << endl;
cout << "it it2 " << *it *it2 << endl;
while(it != nums.end())
{
res.push_back(*it *it2);
cout << "it : " << *it << endl;
cout << "it2 : " << *it2 << endl;
cout << "pushed " << (*it *it2) << " ";
it ;
it2 ;
}
it = nums.begin();
while(it != nums.end())
{
cout << *it << " ";
it;
}
cout << endl;
it2 = res.begin();
while(it2 != res.end())
{
cout << *it2 << " ";
it2;
}
cout << endl;
` 上面的輸出是:
it2 -> 1
it it2 3
it : 2
it2 : 17858448
pushed 17858450 it : 3
it2 : 17825984
pushed 17825987 1 2 3
1 3 17825987
我不明白為什么 *it2 的值在回圈外是正常的,但在回圈內卻顯示地址。
我試圖使用向量找到一維陣列的運行總和。我正在學習迭代器,因此有興趣了解上述代碼為何不起作用的確切原因。
uj5u.com熱心網友回復:
這些不是地址,它們是垃圾整數。
您的代碼正在遭受迭代器失效。當您將一個專案添加到向量時,您可能會使指向它的任何迭代器失效。發生這種情況是因為向向量添加元素可能會導致向量重新分配用于保存其元素的記憶體。如果發生這種情況,那么您將得到一個不再指向正確記憶體的迭代器,因此您將獲得垃圾值。
簡單的解決方法是為此代碼使用整數偏移量而不是迭代器
vector<int>::iterator it = nums.begin();
size_t off2 = 0;
it;
cout << "res[off2] -> " << res[off2] << endl;
cout << "it res[off2] " << *it res[off2] << endl;
while(it != nums.end())
{
res.push_back(*it res[off2]);
cout << "it : " << *it << endl;
cout << "res[off2] : " << res[off2] << endl;
cout << "pushed " << (*it res[off2]) << " ";
it ;
off2 ;
}
盡管由于您似乎總是使用最后一項,因此res更簡單的修復方法是使用res.back(). 沒有給出的印刷
vector<int>::iterator it = nums.begin();
it;
while(it != nums.end())
{
res.push_back(*it res.back());
it ;
}
這篇文章的早期版本是不正確的,感謝 Pepijn 讓我直截了當。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/537147.html
標籤:C 向量迭代器运行时错误
上一篇:學習LearnOpenGL第13章后,基于Phong模型得到奇怪的光照結果
下一篇:ceil函式如何在C 中作業?
