Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replacing an element in a std::vector without operator=

Tags:

c++

stdvector

If I emplace an element into a std::vector by using emplace or emplace_back, the element will be constructed without needing an operator=.

Now I already have a std::vector with elements, and I want to set an element at an index to a new value. This is my current solution, a new solution should behave the same:

std::vector<Type> vec;
// ... fill the vector
for (int value = 0; value <= 10; ++value)
  vec.emplace_back( Type(value) );
// replace at index
int index = 5;
Type newelement {30};
vec.erase( vec.begin() + i );
vec.insert( vec.begin() + i, newelement );

But I obviously don't want to do just that, as that moves all the other elements in the std::vector around, which makes an O(1) complexity task take O(n) time.

Edit: I changed the code snipped to use insert, which is how it actually is in my current code. I now realize that I am confused by not knowing the difference between insert and emplace. Maybe clarifying that would answer this question, too.

like image 459
Daniel Bauer Avatar asked Aug 28 '26 09:08

Daniel Bauer


1 Answers

I think you can just use vec[index] = Type(30); which uses move assignment because the new element is temporary. You need move assignment anyway for std::erase.

If for some reason you want to name the temporary element, you could instead use vec[index] = std::move(newelement);.

like image 142
Henk Avatar answered Aug 31 '26 00:08

Henk