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 ?
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.
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>
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With