3 ms·
> 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>&
by hcrisp 3y ago
> 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?!
- flangola7 3y agoI know you are, but what am I? - A rack of GPUs somewhere
- verdverm 3y agotechnically TPUs for Bard
- zvolsky 3y agoDoesn'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.
- klyrs 3y agoPushing 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