If I have two std::deque
s, and I want to move the first n
objects from the beginning of one to the beginning of the other, what is the best way to do that? Doing the following:
template <typename T>
void fn(std::deque<T>& src)
{
std::deque<T> storage;
size_t i = /* some calculated value between 0 and src.size() */;
storage.insert(storage.begin(), src.begin(), src.begin()+i);
src.erase(src.begin(), src.begin()+i);
// ... other stuff ...
}
would create copies of the T objects. I guess I could do something like (not tested, as example only):
template <typename T>
void fn(std::deque<T>& src)
{
std::deque<T> storage;
size_t i = /* some calculated value between 0 and src.size() */;
for (auto& it = std::reverse_iterator<decltype(src.begin()>(src.begin()+i)
; it != std::reverse_iterator<decltype<src.begin()>(src.begin())
; ++it)
{
storage.push_front(std::move(*it));
}
src.erase(src.begin(), src.begin()+i);
// ... other stuff ...
}
but I'm wondering, is there an algorithm that would already handle this?
Performance, mainly. An std::deque has all of the functionality of std::vector , at least for normal use, but indexing and iterating over it will typically be somewhat slower; the same may hold for appending at the end, if you've used reserve .
std::move is actually just a request to move and if the type of the object has not a move constructor/assign-operator defined or generated the move operation will fall back to a copy.
std::move is used to indicate that an object t may be "moved from", i.e. allowing the efficient transfer of resources from t to another object. In particular, std::move produces an xvalue expression that identifies its argument t . It is exactly equivalent to a static_cast to an rvalue reference type.
Unlike lists, deques don't include a . sort() method to sort the sequence in place. This is because sorting a linked list would be an inefficient operation.
Use a move iterator by calling std::make_move_iterator
:
storage.insert(storage.begin(),
std::make_move_iterator(src.begin()),
std::make_move_iterator(src.begin()+i));
src.erase(src.begin(), src.begin()+i);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With