iter_swap() versus swap() — what's the difference?

后端 未结 6 1987
陌清茗
陌清茗 2020-12-03 00:24

MSDN says:

swap should be used in preference to iter_swap, which was included in the C++ Standard for backward compatibility

6条回答
  •  有刺的猬
    2020-12-03 01:06

    You have hit on the key distinction.

    swap(*a, *b) is a global function that resets all pointers pointing to *a to point to what was the contents of *b and vice versa. It's the old tmp = a, a = b, b = tmp swap.

    iter_swap is for the more limited case of modifying the underlying objects being iterated over to affect the structures of which they were a part. If *a and *b were part of the same linked list, it was sufficient for iter_swap to simply swap their positions in the list. This is an advantage for when you want to simply sort a list without invalidating/changing external pointers to objects in the list. If I have a pointer to a user object I don't care if you sort the list of user objects, I don't want my idea of who is the "current" user to change, so list sort better not use swap.

提交回复
热议问题