advertisement
Premier Club Log In/Registration
  Include Code  Search Tips
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   SKILLBUILDING  |   TIP BANK  |   SOURCEBANK  |   FORUMS  |   NEWSLETTERS
Browse DevX
Have you ever find yourself reinventing the wheel by implementing readily available algorithms, containers or other library components? What were your motives? Was it worth the trouble? Tell us about it in the c++.general discussion group.
Partners & Affiliates
advertisement
advertisement
advertisement
Average Rating: 2.5/5 | Rate this item | 4 users have rated this item.
 

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.  


advertisement
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.

  Next Page: Step 2: Swapping Without a Temporary
Page 1: IntroductionPage 2: Step 2: Swapping Without a Temporary
Please rate this item (5=best)
 1  2  3  4  5
advertisement
Advertising Info  |   Member Services  |   Permissions  |   Contact Us  |   Help  |   Feedback  |   Site Map  |   Network Map  |   About