gpt4 book ai didi

c++ - iter_swap() 与 swap() - 有什么区别?

转载 作者:IT老高 更新时间:2023-10-28 12:30:59 27 4
gpt4 key购买 nike

MSDN says :

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

但是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.

那么哪一个是正确的?我应该使用 iter_swap,还是应该使用 swap? (iter_swap 只是为了向后兼容吗?)为什么?

最佳答案

标准本身很少提及iter_swap:

  • 应该有swap(*a, *b)的效果,虽然没有规定必须这样实现。
  • 取消引用的值 *a*b 必须是“可交换的”,这意味着 swap(*a, *b) 必须是有效的,因此取消引用的类型必须相同,尽管迭代器类型不必相同。
  • iter_swap 需要在std::reverse 的实现中使用。没有对任何其他算法提出这样的要求,所以这似乎很奇怪。

what sehe had found来自 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).

所有这些似乎都表明它是过去的产物。

关于c++ - iter_swap() 与 swap() - 有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14024228/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com