是否可以假定STL向量存储始终是连续的? [英] Is it safe to assume that STL vector storage is always contiguous?

查看:122
本文介绍了是否可以假定STL向量存储始终是连续的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果你有一个已经调整大小的STL向量,是否可以取元素0的地址,并假设向量的其余部分将在内存中?

If you have an STL vector which has been resized, is it safe to take the address of element 0 and assume the rest of the vector will follow in memory?

例如

vector<char> vc(100);
// do some stuff with vc
vc.resize(200);
char* p = &vc[0];
// do stuff with *p


推荐答案

从C ++ 03标准(23.2.4.1):

From the C++03 standard (23.2.4.1):


向量的元素连续存储
,如果v是
向量,其中T是除了bool之外的某些
类型,则它遵守
身份& v [n] ==& v [0] + n for
all 0< = n<

The elements of a vector are stored contiguously, meaning that if v is a vector where T is some type other than bool, then it obeys the identity &v[n] == &v[0] + n for all 0 <= n < v.size().

但是请注意,在向其添加元素之后,数组将被重新分配(无效任何指针和迭代器)。

But watch out for the array being reallocated (invalidating any pointers and iterators) after adding elements to it.

这篇关于是否可以假定STL向量存储始终是连续的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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