C++ Reference: Standard C++ Library reference: Containers: map: map: swap

C++官网参考链接:https://cplusplus.com/reference/map/map/swap/

公有成员函数
<map>
std::map::swap
void swap (map& x);
交换内容
用x的内容交换容器的内容,x是另一个相同类型的map。大小可能不同。
在调用这个成员函数之后,这个容器中的元素是在调用之前在x中的元素,而x中的元素是在this中的元素。所有iterators、references和pointers对于交换的对象仍然有效。
注意,存在一个具有相同名称、swap的非成员函数,用行为类似于此成员函数的优化重载该算法。
C++98
内部容器allocators和比较对象(comparison objects)是否交换未定义。
C++11
没有定义内部容器allocators是否交换,除非适当的allocator trait显式指示它们将传播(propagate)。
内部比较对象(comparison objects)总是使用swap进行交换。

形参 
x
与此相同类型的另一个map容器(即具有相同的模板形参,Key、T、Compare和Alloc),其内容与this容器的内容交换。

返回值
没有返回值。

用例
// swap maps
#include <iostream>
#include <map>

int main ()
{
  std::map<char,int> foo,bar;

  foo['x']=100;
  foo['y']=200;

  bar['a']=11;
  bar['b']=22;
  bar['c']=33;

  foo.swap(bar);

  std::cout << "foo contains:\n";
  for (std::map<char,int>::iterator it=foo.begin(); it!=foo.end(); ++it)
    std::cout << it->first << " => " << it->second << '\n';

  std::cout << "bar contains:\n";
  for (std::map<char,int>::iterator it=bar.begin(); it!=bar.end(); ++it)
    std::cout << it->first << " => " << it->second << '\n';

  return 0;
}
输出:

复杂度
常量。

iterator的有效性
所有指向两个容器中元素的iterators、pointers和references仍然有效,但现在指向另一个容器中的元素,并在其中迭代。
注意,结束iterator不指向元素,可能会无效。

数据竞争
容器和x都被修改了。
调用不会访问任何包含的元素(参见上面的iterator的有效性)。

异常安全
如果两个容器中的allocators比较相等,或者它们的allocator traits表明allocators将传播(propagate),则该函数永远不会抛出异常(无抛出保证)。
否则,它将导致未定义的行为。 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

weixin_40186813

你的能量无可限量。

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值