假设 STL 向量存储总是连续的是否安全?

2023-05-08C/C++开发问题
2

本文介绍了假设 STL 向量存储总是连续的是否安全?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

限时送ChatGPT账号..

如果您有一个已调整大小的 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所有 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 向量存储总是连续的是否安全?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

无法访问 C++ std::set 中对象的非常量成员函数
Unable to access non-const member functions of objects in C++ std::set(无法访问 C++ std::set 中对象的非常量成员函数)...
2024-08-14 C/C++开发问题
17

从 lambda 构造 std::function 参数
Constructing std::function argument from lambda(从 lambda 构造 std::function 参数)...
2024-08-14 C/C++开发问题
25

STL BigInt 类实现
STL BigInt class implementation(STL BigInt 类实现)...
2024-08-14 C/C++开发问题
3

使用 std::atomic 和 std::condition_variable 同步不可靠
Sync is unreliable using std::atomic and std::condition_variable(使用 std::atomic 和 std::condition_variable 同步不可靠)...
2024-08-14 C/C++开发问题
17

在 STL 中将列表元素移动到末尾
Move list element to the end in STL(在 STL 中将列表元素移动到末尾)...
2024-08-14 C/C++开发问题
9

为什么禁止对存储在 STL 容器中的类重载 operator&amp;()?
Why is overloading operatoramp;() prohibited for classes stored in STL containers?(为什么禁止对存储在 STL 容器中的类重载 operatoramp;()?)...
2024-08-14 C/C++开发问题
6