如果您有一个已调整大小的 STL vector ,是否可以安全地获取元素 0 的地址并假设该 vector 的其余部分将跟随在内存中?
例如
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):
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().
(*) ...但要注意在向其添加元素后重新分配的数组(使任何指针和迭代器无效)。
关于c++ - 假设 STL vector 存储总是连续的是否安全?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/247738/