Browse DevX
Sign up for e-mail newsletters from DevX


Choosing the Right swap() Implementation

Though the Standard Template Library offers a generic swap() algorithm, there are several other implementations from which to choose. Which implementation best suits your program's needs? This month's solution shows you how to evaluate each of them, enabling you to utilize each implementation to its greatest benefit.




Building the Right Environment to Support AI, Machine Learning and Deep Learning

wap() is one of those tricky algorithms that has several implementations, each of which offers its own advantages and disadvantages. In the following sections I will show why familiarity with these implementations may be beneficial, albeit for different reasons than you might think.

The Standard Template Library offers a ready-made generic swap() algorithm (in the form of std::swap() which is defined in <algorithm>). Still, there are several other implementations of this algorithm. How do you choose which implementation to use? On which criteria should your evaluation be based?

Familiarize yourself with other implementations of swap(). Then, base your evaluation on the following criteria: performance, ease of maintenance, and genericity.

Step 1: Textbook swap()
The implementation of the plain, vanilla swap() algorithm is straightforward: take two arguments of the same type, copy the first one to a temporary variable, assign the second to the first, and finally, assign the temporary value to the second. Here is the complete function template:

template<class T> void v_swap(T& t1, T& t2)//plain vanilla { T temp=t1; t1=t2; t2=temp; }

This implementation has a prominent advantage: it's generic. As such, it's applicable to built-in types and user-defined types alike. Not very surprisingly, this is exactly how the std::swap() is implemented so there's no need to reinvent the wheel if you wish to use this version. What about performance? In order to evaluate it, let's compare this implementation to other implementations.

Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



Thanks for your registration, follow us on our social networks to keep up-to-date