views:

351

answers:

3

I've read that all stl containers provide a specialisation of the swap algorithm so as to avoid calling the copy constructor and two assignment operations that the default method uses. However, when I thought it would be nice to use a queue in some code I was working on I noticed that (unlike vector and deque) queue doesn't provide this method? I just decided to use a deque instead of a queue, but still I'm interested to know why this is?

+3  A: 

C++0x will add swap to container adapters like std::queue. I could only speculate why it is missing from the current standard. In this discussion someone proposes a workaround:

There is a solution since the standard makes the needed parts protected, called inheritance. [just don't destruct via the std adaptors] create a templated struct inheriting the desired adaptor, provide just the constructors and forward the args to the adaptor class, writing a swap member is a snap since the required items are protected members of the standard adaptors.

lothar
The question was "is there a reason it's missing?"
Jamie Cook
+1  A: 

I'm sure that they were left out as an oversight. In all fairness, I use std::queue and std::stack quite a bit and have never had to swap two. I think your use of a deque instead of a queue is fine. Something like typedef std::deque<MyType> QueueType should give enough of a hint how the container should be used.

rlbond
I'm maintaining two sets of elements that require processing, the current set and the set to process on the next round, so I need to swap the populated nextQueue in place of the depleted currentQueue at the end of each round. Strictly speaking they don't have to be queues at all... they could just be vectors actually... hmmm
Jamie Cook
Have you considered having two pointers to queues, and swapping them instead?
rlbond
@rlbond When the swap method is defined properly the containers merely swap their internal pointers so it's effectively the same thing... and I hate using vector<blah>* vec = new vector(bar); I just think it's ugly :)
Jamie Cook
@Jamie you don't actually have to do that, you can say vector<blah> a, b; vector<blah>* current =
rlbond
A: 

swap is a funding technique which permit the borrower to access one market then exchange the liability for another type of liability

vineet tyagi