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()
将使指向矢量的所有迭代器/指针无效。