Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Resizing std::vector without destroying elements

Tags:

c++

c++11

vector

I am using all the time the same std::vector<int> in order to try to avoid allocating an deallocating all the time. In a few lines, my code is as follows:

std::vector<int> myVector;
myVector.reserve(4);

for (int i = 0; i < 100; ++i) {
    fillVector(myVector);
    //use of myVector
    //....
    myVector.resize(0);
}

In each for iteration, myVector will be filled with up to 4 elements. In order to make efficient code, I want to use always myVector. However, in myVector.resize() the elements in myVector are being destroyed. I understand that myVector.clear() will have the same effect.

I think if I could just overwrite the existing elements in myVector I could save some time. However I think the std::vector is not capable of doing this.

Is there any way of doing this? Does it make sense to create a home-grown implementation which overwrites elements ?

like image 323
Javi Avatar asked Dec 12 '22 07:12

Javi


2 Answers

Your code is already valid (myVector.clear() has better style than myVector.resize(0) though).

'int destructor' does nothing.
So resize(0) just sets the size to 0, capacity is untouched.

like image 190
Jarod42 Avatar answered Dec 13 '22 20:12

Jarod42


Simply don't keep resizing myVector. Instead, initialise it with 4 elements (with std::vector<int> myVector(4)) and just assign to the elements instead (e.g. myVector[0] = 5).

However, if it's always going to be fixed size, then you might prefer to use a std::array<int, 4>.

like image 44
Joseph Mansfield Avatar answered Dec 13 '22 21:12

Joseph Mansfield