Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
342 views
in Technique[技术] by (71.8m points)

c++ - Replacing an element in a std::vector without operator=

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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);.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...