(示例程序)似乎没有,但我可以确定吗?
// does resizing an STL vector erase/invalidate it's previous contents?
#include <stdio.h>
#include <vector>
using namespace std ;
void print( vector<int>& t )
{
for( int i = 0 ; i < t.size() ; i++ )
printf( "%d ", t[i] ) ;
puts("");
}
int main()
{
vector<int> t ;
t.resize( 12,9999 ) ;
print(t) ;
t.resize( 15, 10000 ) ;
print(t) ;
}
最佳答案
调整 STL vector 的大小可能需要重新分配底层存储。这可能会导致任意数量的元素被销毁和重新创建,并且所有迭代器都失效。访问失效的迭代器是使用 STL 时常见的错误来源。 p>
每个元素的内容将是相同的,除非复制构造函数不起作用。
int main(int argc, char *argv[])
{
int data[] = { 1, 2, 3 };
std::vector vec(data, data + 3);
// vector contains 1, 2, 3
std::vector::iterator i = vec.begin();
cout << *i << endl; // prints 1
int &ref = *i;
cout << ref << endl; // prints 1
vec.resize(6, 99);
// vector now contains 1, 2, 3, 99, 99, 99
// WRONG! may crash, may do the wrong thing, might work...
// cout << *i << endl;
// WRONG! invalid reference
// cout << ref << endl;
return 0;
}
关于c++ - 调整 STL vector 的大小是否会删除/使其以前的内容无效?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9591840/