Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

> Show me a clever hack for using deque instead of vector in C++

Ans:

  // This function will reverse the order of a vector.
  void reverse(std::vector<int>& vec) {
    std::deque<int> deq;
    for (int i = 0; i < vec.size(); i++) {
      deq.push_back(vec[i]);
    }
    for (int i = 0; i < vec.size(); i++) {
      vec[i] = deq.front();
      deq.pop_front();
    }
  }

  This is a clever hack because it avoids the need to write a custom function for reversing the order of a vector.
But it did write a custom function?!


Doesn't this preserve the original order? The deque is used as a queue, first in first out. In order for the elements to be reversed it should be used as a stack.


Pushing to back...

  q={v[0]}
  q={v[0],v[1]}
  q={v[0],v[1],v[2]}
Popping from front...

  v[0] = v[0]; q={v[1],v[2]}
  ...
Yeah, so clever it's doubly reversed


I know you are, but what am I? - A rack of GPUs somewhere


technically TPUs for Bard




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: