IteratorPointer 失效
指向 std::vector
的迭代器和指標可能變為無效,但僅在執行某些操作時才會失效。使用無效的迭代器/指標將導致未定義的行為。
使迭代器/指標無效的操作包括:
-
任何更改
vector
的capacity
的插入操作都將使所有迭代器/指標無效 :vector<int> v(5); // Vector has a size of 5; capacity is unknown. int *p1 = &v[0]; v.push_back(2); // p1 may have been invalidated, since the capacity was unknown. v.reserve(20); // Capacity is now at least 20. int *p2 = &v[0]; v.push_back(4); // p2 is *not* invalidated, since the size of `v` is now 7. v.insert(v.end(), 30, 9); // Inserts 30 elements at the end. The size exceeds the // requested capacity of 20, so `p2` is (probably) invalidated. int *p3 = &v[0]; v.reserve(v.capacity() + 20); // Capacity exceeded, thus `p3` is invalid.
Version >= C++ 11
auto old_cap = v.capacity();
v.shrink_to_fit();
if(old_cap != v.capacity())
// Iterators were invalidated.
-
任何不增加容量的插入操作仍然會使指向插入位置的元素並超過它的迭代器/指標無效。這包括
end
迭代器:vector<int> v(5); v.reserve(20); // Capacity is at least 20. int *p1 = &v[0]; int *p2 = &v[3]; v.insert(v.begin() + 2, 5, 0); // `p2` is invalidated, but since the capacity // did not change, `p1` remains valid. int *p3 = &v[v.size() - 1]; v.push_back(10); // The capacity did not change, so `p3` and `p1` remain valid.
-
任何刪除操作都將使指向已刪除元素的迭代器/指標以及經過刪除元素的任何元素無效。這包括
end
迭代器:vector<int> v(10); int *p1 = &v[0]; int *p2 = &v[5]; v.erase(v.begin() + 3, v.end()); // `p2` is invalid, but `p1` remains valid.
-
operator=
(複製,移動或其他)和clear()
將使指向向量的所有迭代器/指標無效。