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

后端 未结 6 1997
陌清茗
陌清茗 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:08

    The standard itself has very few mentions of iter_swap:

    • It should have the effect of swap(*a, *b), although there is no stipulation that it must be implemented that way.
    • The dereferenced values *a and *b must be "swappable", which implies that swap(*a, *b) must be valid, and thus the dereferenced types must be identical, although the iterator types do not have to be.
    • iter_swap is required to be used in the implementation of std::reverse. No such requirement is placed on any other algorithm, so this seems to be an oddity.

    To borrow what sehe had found from the SGI docs:

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

    All of these seem to suggest that it is an artifact of the past.

提交回复
热议问题