Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

MSDN says:

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

But comp.std.c++ says:

Most STL algorithms operate on iterator ranges. It therefore makes sense to use iter_swap when swapping elements within those ranges, since that is its intended purpose --- swapping the elements pointed to by two iterators. This allows optimizations for node-based sequences such as std::list, whereby the nodes are just relinked, rather than the data actually being swapped.

So which one is correct? Should I use iter_swap, or should I use swap? (Is iter_swap only for backwards compatibility?) Why?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
143 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...