Reputation: 1728
I have a std::vector. I assign this vector like
vec.assign(20000, 0);
Now I have an additional array, which I want to insert into the vector. But NOT just like insert, more replace elements in the vector.
uint8_t a[] = {1,2,3,4,5,6,7,8};
Move that array into the vector on position x - x+8 without allocating new memory.
What I tried and works is of course
vec.insert(start, a, a+8);
But there I am allocating new memory and the size of the vector changes, which is not supposed to happen. Yes, I could delete, the entries, which are too much, but there's still the problem, that I am allocating more memory. Isn't there a possibility, to just replace the array with the contents of the vector? Smth like that:
vec.replace(start, a, a+8);
I wanted to avoid replacing each element, cause I am afraid that could take too long.
What do you think? Is there a way to do that? Have you had that problem before, too? How did you fix it?
Upvotes: 1
Views: 124
Reputation: 8027
Simple
#include <algorithm>
std::copy(a, a + 8, vec.begin());
Copies elements from a
upto a + 8
and replaces the elements starting at vec.begin()
.
I think you are wrong to worry about efficiency. The solution above does replace each element, and would likely be no more nor no less efficient than if you wrote the replacement code yourself. If the code above has any advantage it is clarity, a much overlooked advantage.
Upvotes: 6