user63898 user63898 - 3 months ago 6
C++ Question

std vector size keep ground Although i insert in the same indexs

Something wired i see here with std vector
I have
variable that its value is dynamically changes but always under 20
dynamicSizeToInsert in the example.
why the vector size keeps growing ?

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
}


i want to keep my vector side 5 elements big
and that new value will run over other value in the same index .

Answer

std::vector::insert, as the name suggests, inserts elements at the specified position.

When c == dynamicSizeToInsert, c is set to 0. So now, v.size() == 5. Now this lines executes:

v.insert(v.begin() + c, c);

This will insert 0 at posistion v.begin() + 0, which is position 0 and it will offset every other element (it will not replace the element at position 0), and so the vector keeps growing.


Instead of using insert, use 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++;
}
Comments