博客统计信息

用户名:lhuashang
文章数:32
评论数:41
访问量:118281
无忧币:20
博客积分:808
博客等级:3
注册日期:2008-04-27

我的技术圈(3)

更多>>
STL 容器内存紧缩方法
2009-09-25 01:27:47
标签:STL C++ 职场 休闲
   Sever开发者一般不是非常喜欢用STL容器来管理内存数据,原因可能是STL容器的内存回收策略未必非常适合Server:Server常驻内存,非常希望用过的内容能够很快的回收。
 
  使用vector的push_back 插入10000个对象后,在吧这10000个对象pop_back出去,申请的10000个对象的内存空间实际上并没有立刻释放掉。STL容器仍然保留这部分对象以备后续使用。
 
  如果确实需要紧缩空vector的内存,可以使用vector的swap方法。
  如vector A为需要紧缩的容器,可以建立一个临时的vector B, 调用B.swap(A).
  因为B为临时对象,可以立即释放,而A和B的内容交换了,即A是B。达到了内存紧缩的目的。
 
 附上代码一段:
 
 
#include <vector>
#include <iostream>

using namespace std;

typedef struct Block{
    char dummy[1024];    
}Block;

typedef vector<Block> BlkVector;

void show_space(BlkVector * blk_vec)
{
        cout<<"size = "<< blk_vec->size() << ", capacity = " << blk_vec->capacity() << endl;        
}

int main(int argc, char *args[])
{
        BlkVector bv;
        Block b;
        show_space(&bv);
        bv.push_back(b);
        show_space(&bv);
        for(int i = 0 ; i < 1000 ; i++)
        {
                bv.push_back(b);
        }
        show_space(&bv);
        
        while( bv.size() > 0 )
        {
                bv.pop_back();
        }
        show_space(&bv);
        BlkVector().swap(bv);
        show_space(&bv);
        
}                    
 
vector::swap public member function
void swap ( vector<T,Allocator>& vec );
Swap content
Exchanges the content of the vector by the content of vec, which is another vector of the same type. Sizes may differ.

After the call to this member function, the elements in this container are those which were in vec before the call, and the elements of vec are those which were in this. All iterators, references and pointers remain valid for the swapped vectors.

Notice that a global algorithm function exists with this same name, swap, and the same behavior.
分享至
更多
一键收藏,随时查看,分享好友!
0人
了这篇文章
类别:未分类┆技术圈()┆阅读()┆评论() ┆ 推送到技术圈返回首页

文章评论

 
 

发表评论            

【技术门诊】专家解析:软考重点难点及应试技巧
昵  称:
登录  快速注册
验证码:

请点击后输入验证码博客过2级,无需填写验证码

内  容: