保证向量指针位置? [英] vector pointer locations guaranteed?

查看:33
本文介绍了保证向量指针位置?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个整数向量,

Suppose I have a vector of ints,

std::vector<int> numbers;

用一堆值填充,然后我说这样做(其中条目存在于 43)

that is populated with a bunch of values, then I say do this (where an entry exists at 43)

int *oneNumber = &numbers[43];

oneNumber 是否保证始终指向索引 43 处的 int,即使我将数字调整为 numbers.resize(46) 之类的内容?

Is oneNumber guaranteed to always be pointing at the int at index 43, even if say I resize numbers to something like numbers.resize(46)?

我不是 100% 确定这里的预期行为是什么,我知道向量保证是连续的,但不确定这种连续性是否也意味着向量中的所有索引在其整个生命周期中都将保持在同一位置.

I'm not 100% sure what expected behaviour is here, I know vectors are guaranteed to be contiguous but not sure if that continuity would also mean all the indices in the vector will remain in the same place throughout its life.

推荐答案

oneNumber 是否保证始终指向索引 43 处的 int

Is oneNumber guaranteed to always be pointing at the int at index 43

是的,这是由标准保证的.

Yes, this is guaranteed by the standard.

即使说我将数字调整为 numbers.resize(46) 之类的东西?

even if say I resize numbers to something like numbers.resize(46)?

没有.一旦您对向量调整大小、添加或删除任何内容,它的所有地址和迭代器都将失效.这是因为向量可能需要重新分配新的内存位置.

No. Once you resize, add, or remove anything to the vector, all addresses and iterators to it are invalidated. This is because the vector may need to be reallocated with new memory locations.

这篇关于保证向量指针位置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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