首先來看一組代碼:
?
iterator insert(iterator pos, const T& x)
{// 擴容if (_finish == _end_of_storage){size_t len = pos - _stare;reserve(capacity() == 0 ? 4 : capacity() * 2);pos = _stare + len;}iterator end = _finish - 1;while (end >= pos){*(end + 1) = *end;--end;}*pos = x;++_finish;return pos;
}
這是關于實現insert函數的一組代碼。對pos迭代器指向的位置進行插入數據。現在給出一組測試用例:
?
void test_vector2()
{std::vector<int> v;v.push_back(1);v.push_back(2);v.push_back(3);v.push_back(4);v.push_back(5);Cao::print_container(v);/*v.insert(v.begin() + 2, 30);print_vector(v);*/int x;cin >> x;auto p = find(v.begin(), v.end(), x);if (p != v.end()){p = v.insert(p, 40);(*(p + 1)) *= 10;}Cao::print_container(v);
}
來看運行結果:
p本來指向的是1的位置,但是現在卻是40乘10,這就是因為迭代器失效的原因。當進行insert插入之后返回的迭代器已經不指向原來的位置。所以對insert插入之后的pos迭代器進行操作就會引起指向錯誤。所以得出,經過insert之后的迭代器就會失效。不要直接進行訪問。如若訪問,一定要更新失效的迭代器之后在進行訪問。?
修改后的代碼:
void test_vector2()
{std::vector<int> v;v.push_back(1);v.push_back(2);v.push_back(3);v.push_back(4);v.push_back(5);Cao::print_container(v);int x;cin >> x;auto p = find(v.begin(), v.end(), x);if (p != v.end()){p = v.insert(p, 40);(*(p + 1)) *= 10;}Cao::print_container(v);
}
對p這個迭代器進行修正,就得出了想要的結果。
因此在平時使用vector時,需要特別注意此類迭代器失效問題,因此的運行錯誤。?