What's the point of iter_swap?

后端 未结 2 1289
天命终不由人
天命终不由人 2020-12-30 19:48

I was just wondering, why would anybody write this:

std::iter_swap(i, k);

instead of this?

std::swap(*i, *k);   // saved a          


        
相关标签:
2条回答
  • 2020-12-30 20:06

    From the SGI docs (here):

    [1] Strictly speaking, iter_swap is redundant. It exists only for technical reasons: in some circumstances, some compilers have difficulty performing the type deduction required to interpret swap(*a, *b).

    0 讨论(0)
  • 2020-12-30 20:23

    To answer your second question, the using + swap allows the compiler to use user-defined swap functions that may be more efficient than the default implementation (by using ADL). Explicitly saying std::swap inhibits ADL and any custom swap methods it maybe have been able to find.

    As for iter_swap it's presumably there to use in templates and clearly indicate intention rather than a swap that might indicate you expect a pointer.

    0 讨论(0)
提交回复
热议问题