STL algorithm中的swap 函数使用

1.swap函数执行会调用容器内数据类型的,拷贝构造和赋值函数调用
对自定义类型使用STL algorithm中的swap函数,会调用自定义的类型的拷贝构造函数一次,赋值函数两次;自定义类型中没有定义那么就会使用默认的拷贝构造函数和赋值函数。 如果是容器,那么会遍历容易进行赋值。
2.swap函数可用于清空vector和string类型容器分配的内存空间
对于vector, string, basic_string<wchar_t>容器clear后不会释放占有的内存空间capacity,而只是减少了内存上的数据元素size。
如果要对vector,string进行清空不再使用的内存,那么需要调用swap来清理掉。其它的stl容器调用clear时候是会清空内存空间的。


STL 中swap源码:
// TEMPLATE FUNCTION swap (from <algorithm>)
template<class _Ty> inline
 void swap(_Ty& _Left, _Ty& _Right)
 { // exchange values stored at _Left and _Right
 _Ty _Tmp = _Move(_Left);
 _Left = _Move(_Right);
 _Right = _Move(_Tmp);
 }


// 测试例子
#include <iostream>
#include <vector>
#include <string>
#include <queue>
#include <stack>
#include <map>
#include <set>
#include <algorithm>
struct tagStudent
 {
  int m_nID;
  int m_nScore;
  tagStudent& operator =(const tagStudent &b)
  {
   this->m_nID = b.m_nID;
   this->m_nScore = b.m_nScore;
   return *this;
  }
  tagStudent( const tagStudent &b)
  {
   this->m_nID = b.m_nID;
   this->m_nScore = b.m_nScore;
  }

  tagStudent( int nID, int nScore )
  {
   this->m_nID = nID;
   this->m_nScore = nScore;
  }
 
 };
void main()
{
    tagStudent AStudent(2, 20);
    tagStudent BStudent(3, 80);
    // 在tagStudent中的拷贝构造和赋值函数中打断点会发现,拷贝构造调用了一次,赋值函数调用了两次
    std::swap( AStudent, BStudent);
    int x = 10;  
    //vector<int> myContainer(10000, x); 
    string myContainer(10000,'\0');

    //这里打印仅仅是元素的个数不是内存大小  
    cout << "myContainer size :"  << myContainer.size() << ", capacity:"<< myContainer.capacity()<< endl; 

    myContainer.clear();;
    cout << "after clear size :"  << myContainer.size() << ", capacity:"<< myContainer.capacity()<< endl;  
    //swap交换函数释放内存:vector<T>().swap(X);  
    //T:int ; myvertor代表X  
    //vector<int>().swap(myContainer);
    string().swap(myContainer); 

    //两个输出仅用来表示swap前后的变化  
    cout << "after swap size :"  << myContainer.size() << ", capacity:"<< myContainer.capacity()<< endl;  
    // 并不是所有的STL容器的clear成员函数的行为都和vector一样。事实上,其他容器的clear成员函数都会释放其内存。
 }


  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值