1. 程式人生 > >C++ 之路 vector的記憶體管理與效率

C++ 之路 vector的記憶體管理與效率

    好長時間沒有寫部落格了,重新開始寫又有一點不一樣的感覺,有點悵然若失,或者說是又有點小期待,一直以來狀態不是很好,但不管如何還是要堅強地、勇敢地走下去。

    言歸正傳

       C++中vector是一項大殺器,相當於可自動變長的陣列,在不改變容量的情況下,其效率相當於陣列,但較於陣列而言他又有更多的優點,首先介紹幾個成員函式與vector容量相關的

  1. size() Returns the number of elements in the vectorThis 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 capacityRequests 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);
}