调整向量的大小无效迭代器? [英] Does resizing a vector invalidate iterators?

查看:155
本文介绍了调整向量的大小无效迭代器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现这个C ++代码:

I found that this C++ code:

vector<int> a;
a.push_back(1);
a.push_back(2);
vector<int>::iterator it = a.begin();
a.push_back(4);
cout << *it;

打印一些大随机数;但是如果你在第3行和第4行之间添加 a.push_back(3),它将打印1.你能向我解释吗?

print some big random number; but if you add a.push_back(3) between 3rd and 4th lines, it will print 1. Can you explain it to me?

推荐答案

使用更仔细的措辞编辑

所有迭代器指向向量。

向量是通过内部分配存储数据的数组来实现的。当向量增长时,该数组可能会耗尽空间,而当数据增长时,向量会分配一个新的更大的数组,将数据复制到该数组,然后删除旧数组。

The vector is implemented by internally allocating an array where the data is stored. When the vector grows, that array might run out of space, and when it does, the vector allocates a new, bigger, array, copies the data over to that, and then deletes the old array.

所以你的旧迭代器,指向旧的内存,不再有效。
如果向量被向下调整大小(例如通过 pop_back()),则使用相同的数组。

So your old iterators, which point into the old memory, are no longer valid. If the vector is resized downwards (for example by pop_back()), however, the same array is used. The array is never downsized automatically.

避免重新分配(和指针无效)的一种方法是调用 vector :: reserve()首先,留出足够的空间,这个复制是不必要的。在你的情况下,如果在第一个 push_back()操作之前调用 a.reserve(3)数组足够大,可以执行 push_back ,无需重新分配数组,因此您的迭代器将保持有效。

One way to avoid this reallocation (and pointer invalidation) is to call vector::reserve() first, to set aside enough space that this copying isn't necessary. In your case, if you called a.reserve(3) before the first push_back() operation, then the internal array would be big enough that the push_back's can be performed without having to reallocate the array, and so your iterators will stay valid.

这篇关于调整向量的大小无效迭代器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆