简体   繁体   中英

Queue Swap C++ STL

I want to implement a some functionality, where I will be needing two queues from STL. And I frequently have to do some operations based on input data,and I may need to move all elements from one queue to another and vice versa.But I am thinking that if i maintain reference to two queues,then I can just swap references instead of two queues.So is it possible in C++ that I have two references to two queues, and i can swap those references as per requirement ?How can i do it if possible?Normally i would have done as follow:

Queue<int> Q1;
Queue<int> Q2;
I can swap like:
Queue<int> Q3=Q1;
Q1=Q2;
Q2=Q3;

But it will do entire data copy and can be a very time consuming operation.How can i represent Q1 and Q2 as reference and then perform just swap of reference?

Don't try to be too smart. Just use the straightforward way - std::swap . std::queue is movable, so you won't copy anything, it is already very efficient. Just to ensure this is the case with your own Queue , add assertions:

static_assert(std::is_move_constructible_v<Queue<int>> && std::is_move_assignable_v<<Queue<int>>)

If this is too slaw for your particular case then you can try to come up with something more fancy. But do not try to optimize (especially microoptimize) without benchmarks, because most probable you will fail. With the today's hardware complexity and with the intelligence of today's compilers it very hard to reason about code efficiency without actual benchmarks. Once again, choose a simply way, if this isn't enough (you can know this only by testing/benchmarking) then try something more complicated.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM