Why / when should we prefer to use std :: swap; swap (a, b) on std :: iter_swap (& amp; a, & amp; b)?

advertisements

Why/when should we prefer using std::swap; swap(a, b); over std::iter_swap(&a, &b)?


Since they are completely different your question is a false dichotomy.

They do different things!

  • One swaps value.
  • The other swaps the content of the destination of iterator.

But if you have iterators. It is probably better to use std::iter_swap. Otherwise you can use swap (as long as you have done the using std::swap; locally to the call to swap (otherwise the type dependent lockup for the correct swap may fail).

std::iter_swap(i1, i2);

// Is equivelent to writing.
using std::swap;  // Notice this.
swap(*i1 ,*i2);   // Notice the * in front of the iterator.