std::swap与std::iter_swap 交换元素

std::swap

std::swap 用于交换2个元素,g++源码如下

  /**
   *  @brief Swaps two values.
   *  @param  __a  A thing of arbitrary type.
   *  @param  __b  Another thing of arbitrary type.
   *  @return   Nothing.
  */
  template<typename _Tp>
    inline void
    swap(_Tp& __a, _Tp& __b)
#if __cplusplus >= 201103L
    noexcept(__and_<is_nothrow_move_constructible<_Tp>,
                is_nothrow_move_assignable<_Tp>>::value)
#endif
    {
      // concept requirements
      __glibcxx_function_requires(_SGIAssignableConcept<_Tp>)

      _Tp __tmp = _GLIBCXX_MOVE(__a);
      __a = _GLIBCXX_MOVE(__b);
      __b = _GLIBCXX_MOVE(__tmp);
    }

#define _GLIBCXX_MOVE(__val) std::move(__val)

_GLIBCXX_MOVE()宏实际上是std::move。因此,swap核心代码相当于:

template<typename Tp>
inline void swap(Tp& a, Tp& b)
{
    Tp tmp = std::move(a);
    a = std::move(b);
    b = std::move(tmp);
}

也就是说,通过一个临时变量tmp,交换a、b的值。

iter_swap

iter_swap用于交换2个迭代器所指元素。g++源码如下

template <class ForwardIterator1, class ForwardIterator2>
inline void iter_swap (ForwardIterator1 a, ForwardIterator2 b)
{
    swap (*a, *b);
}

也就是说,iter_swap的参数,应该是一个迭代器,交换的是迭代器(包括指针)多指向的元素。而iter_swap本身也是利用swap来实现的。

应用示例

利用std::swap, std::iter_swap交换a、b两个元素:

int a = 10, b = 20;

std::swap(a, b);
cout << "a = " << a << ", b = " << b << endl; // 打印 a = 20, b = 10

std::iter_swap(&a, &b);
cout << "a = " << a << ", b = " << b << endl; // 打印 a = 10, b = 20

交换容器中的数据:

vector<string> svec = {"A", "B", "C"};
for_each(svec.begin(), svec.end(), [](const string& str){cout << str;}); // 打印"ABC"
cout << endl;

std::swap(svec[0], svec[2]); // 交换元素svec[0]和svec[2]
for_each(svec.begin(), svec.end(), [](const string& str){cout << str;}); // 打印"CBA"
cout << endl;

std::iter_swap(svec.begin(), svec.begin() + 2); // 交换svec.begin()和svec.begin()+2所指元素
for_each(svec.begin(), svec.end(), [](const string& str){cout << str;}); // 打印"ABC"
cout << endl;

参考

http://www.cplusplus.com/reference/algorithm/iter_swap/
https://blog.csdn.net/zqw_yaomin/article/details/81278948

原文链接: https://www.cnblogs.com/fortunely/p/16114745.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍;

也有高质量的技术群,里面有嵌入式、搜广推等BAT大佬

    std::swap与std::iter_swap 交换元素

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/402676

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年4月21日 上午11:09
下一篇 2023年4月21日 上午11:09

相关推荐