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.
question from:
https://stackoverflow.com/questions/65904997/replacing-an-element-in-a-stdvector-without-operator 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…