Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Better way to move objects from one std::deque to another?

Tags:

c++

c++11

c++14

If I have two std::deques, 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?

like image 851
Adrian Avatar asked Apr 19 '18 19:04

Adrian


People also ask

Is deque slower than vector?

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 .

Does std :: move do a copy?

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.

Why is std :: move necessary?

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.

Is deque sorted?

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.


1 Answers

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);
like image 146
Justin Avatar answered Sep 30 '22 19:09

Justin