Is there any straightforward way to insert or replace multiple elements from &[T]
and/or Vec<T>
in the middle or at the beginning of a Vec
in linear time?
I could only find std::vec::Vec::insert
, but that's only for inserting a single element in O(n)
time, so I obviously cannot call that in a loop.
I could do a split_off
at that index, extend
the new elements into the left half of the split, and then extend
the second half into the first, but is there a better way?
As of Rust 1.21.0,
Vec::splice
is available and allows inserting at any point, including fully prepending:The docs state:
In this case, the lower bound of the slice's iterator should be exact, so it should perform one memory move.
splice
is a bit more powerful in that it allows you to remove a range of values (the first argument), insert new values (the second argument), and optionally get the old values (the result of the call).Replacing a set of items
Getting the previous values
Okay, there is no appropriate method in Vec interface (as I can see). But we can always implement the same thing ourselves.
memmove
When T is Copy, probably the most obvious way is to move the memory, like this:
shuffle
If T is not copy, but it implements Clone, we can append given slice to the end of the Vec, and move it to the required position using swaps in linear time:
iterators concat
Maybe the best choice will be to not modify Vec at all. For example, if you are going to access the result via iterator, we can just build iterators chain from our chunks: