Swapping Without Temporary Storage

21 09 2011

Swapping two variables typically uses a temporary variable. But how do you swap if you are short of storage space? For instance, suppose you have your home keys in your left hand, and a grocery bag in your right hand. If you’re right-handed you’ll need to swap the keys to the other hand in order to open the door, but how do you do that with no temporary storage around?

The following algorithm is perhaps not the most efficient one but it fits the bill perfectly!

template <typename Thing> void Swap( Thing &oneHand,Thing &otherHand )
{
try
{
throw oneHand;
}
catch( Thing falling )
{
oneHand = otherHand;
otherHand = falling;
}
}

Again, the complete code can be found here.

N.B. This article was written tongue firmly in cheek. If you read the code like a story it should appear humorous, but in real world I do not advocate using exceptions as a mechamism for program flow control.

Advertisements

Actions

Information

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s




%d bloggers like this: