Home > Blogs > 30 C++ Tips in 30 Days: Tip # 17 efficient swapping of standard containers and objects

30 C++ Tips in 30 Days: Tip # 17 efficient swapping of standard containers and objects

By  Dec 6, 2007

Topics: Programming, C/C++

There are at least two orthodox methods for swapping the contents of two container objects. Which one is better?

Suppose you want to swap vi and vj. The generic approach is to call the swap() algorithm:

vector <int> vi;
//…fill vi
vector <int> vj;
//…fill vj 
std::swap(vi, vj);

However, most container classes (as well as other types of swappable Standard Library entities such as shared_ptr) have a swap() member function:

vi.swap(vj); //preferable to std::swap(vi,vj); 

Generally speaking, you should use the swap() member function instead of the generic std::swap() algorithm because the member function is optimized for its class type. In some cases, it uses move semantics instead of copying whole objects.

Become an InformIT Member

Take advantage of special member promotions, everyday discounts, quick access to saved content, and more! Join Today.