我在这里看到的东西有标准 vector 我有 其值动态变化但始终小于 20 的变量 示例中的 dynamicSizeToInsert。 为什么 vector 大小不断增长?
std::vector<int> v;
//sometimes its 5 sometimes it is 10 sometimes it is N < 20
int dynamicSizeToInsert = 5
int c = 0;
for(std::vector<int>::size_type i = 0; i != 100; i++) {
if(c == dynamicSizeToInsert )
{
c = 0;
}
v.insert(v.begin() + c, c);
c++;
printf("%d",v.size()) //THIS THINK KEEP growing although i only using vector indexes 0 to 4 allways
}
我想让我的 vector 边 5 个元素大 并且该新值将超过同一索引中的其他值。
最佳答案
std::vector::insert
,顾名思义,在指定位置插入元素。
当c == dynamicSizeToInsert
时,c
设置为0
。所以现在,v.size() == 5
。现在这一行执行:
v.insert(v.begin() + c, c);
这将在位置 v.begin() + 0
处插入 0
,即位置 0
并且它将偏移所有其他元素(它不会替换位置 0
处的元素,因此 vector 会不断增长。
不使用insert
,而是使用operator[]
:
//So that 'v' is the right size
v.resize(dynamicSizeToInsert);
for(std::vector<int>::size_type i = 0; i != 100; i++) {
if(c == dynamicSizeToInsert )
{
c = 0;
}
v[i] = c; //Sets current index to 'c'
c++;
}
关于c++ - std vector size keep ground 虽然我插入相同的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38841950/