C++ 之路 vector的内存管理与效率

    好长时间没有写博客了,重新开始写又有一点不一样的感觉,有点怅然若失,或者说是又有点小期待,一直以来状态不是很好,但不管如何还是要坚强地、勇敢地走下去。

    言归正传


       C++中vector是一项大杀器,相当于可自动变长的数组,在不改变容量的情况下,其效率相当于数组,但较于数组而言他又有更多的优点,首先介绍几个成员函数与vector容量相关的

  1. size() Returns the number of elements in the vector This is the number of actual objects held in the vector, which is not necessarily equal to its storage capacity.(即返回元素个数)
  2. capacity()The size of the currently allocated storage capacity in the vector, measured in terms of the number elements it can hold. Member type size_type is an unsigned integral type.(返回容器容量)
  3. resize(size_type n, value_type val = value_type()Resizes the container so that it contains n elements.
    If n is smaller than the current container size, the content is reduced to its first n elements, removing those beyond (and destroying them).
    If n is greater than the current container size, the content is expanded by inserting at the end as many elements as needed to reach a size of n. If val is specified, the new elements are initialized as copies of val, otherwise, they are value-initialized.
    If n is also greater than the current container capacity, an automatic reallocation of the allocated storage space takes place.
    Notice that this function changes the actual content of the container by inserting or erasing elements from it.(即是将容器大小调整到n,少则补,多则删)
  4. reserve(size_type n
    Request a change in capacity
    Requests that the vector capacity be at least enough to contain n elements.
    If n is greater than the current vector capacity, the function causes the container to reallocate its storage increasing its capacity to n (or greater).
    In all other cases, the function call does not cause a reallocation and the vector capacity is not affected.
    This function has no effect on the vector size and cannot alter its elements.(当当前容量小的时候,调整大小到n,其余情况不做改变)
    以上便是vector与存储容量有关的函数,vector有一个特点即是,一般而言,容量capacity比大小size要多一些,那么需要一些方法来修整这些过剩的空间。

    一下介绍两种方法

①使用“交换技巧”来修整vector过剩空间/内存(shrink to fit)

核心就一句话:vector<int>(ivec).swap(ivec) 原理其实比较简单,vertor<int>(ivec)创建了一个临时变量,这个变量是ivec的一份拷贝,拷贝时只会分配需要的内存,因此就不会有过剩空间,然后通过swap(ivec)交换数据 此时临时变量就持有原来的过剩空间,当语句执行完之后,临时变量被销毁,过剩空间完成释放。

    

②用swap方法强行释放vector所占内存

    和上述原理一样,只不过包装了一下

template <class T> void ClearVector(vector<T>& v)
{
  vector<T> vtTemp;
  vtTemp.swap(v);
}



猜你喜欢

转载自blog.csdn.net/qq_37925512/article/details/80464070
今日推荐