iter_swap()对swap() - 有什么区别? [英] iter_swap() versus swap() -- what's the difference?
问题描述
swap
应优先于iter_swap
以便向后兼容。
swap
should be used in preference toiter_swap
, which was included in the C++ Standard for backward compatibility.
大多数STL算法对迭代器范围。因此,当在这些范围内交换元素时,
使用iter_swap
是有意义的,因为这是它的
预期目的---交换指向的元素两个迭代器。这个
允许优化基于节点的序列,例如std :: list
,其中
节点只是重新链接,而不是实际交换的数据。
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 asstd::list
, whereby the nodes are just relinked, rather than the data actually being swapped.
那么哪一个是正确的呢?我应该使用 iter_swap
,还是应该使用 swap
? (<
So which one is correct? Should I use iter_swap
, or should I use swap
? (Is iter_swap
only for backwards compatibility?) Why?
推荐答案
标准本身很少提及 iter_swap
:
-
交换(* a,* b)
,虽然没有规定必须以这种方式实现。 - code> * a 和
* b
必须是可交换的,这意味着* b)
必须有效,因此取消引用的类型必须是相同的,但迭代器类型不必是 -
需要在
。std :: reverse
的实现中使用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 thatswap(*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 ofstd::reverse
. No such requirement is placed on any other algorithm, so this seems to be an oddity.
借用 发现的 //stackoverflow.com/a/13991936/1435577> stl / iter_swap.html> SGI文档 :
To borrow what sehe had found from the SGI docs:
严格地说,
iter_swap
是多余的。它只存在于技术原因:在某些情况下,一些编译器难以执行解释swap(* a,* b)
所需的类型扣除。
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 interpretswap(*a, *b)
.
所有这些似乎暗示它是过去的神器。
All of these seem to suggest that it is an artifact of the past.
这篇关于iter_swap()对swap() - 有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!