vector shrink_to_fit

xuqing-ICT發表於2014-07-09


#include <bits/stdc++.h>
using namespace std;

int main()
{
    vector<int>vec;
    for(int i = 0 ;i  < 100 ; ++i)
        vec.push_back(i);
    cout << vec.size() << endl; //100
    cout << vec.capacity() << endl; //128
    vec.erase(vec.begin()+10,vec.end()); //改變了size,但是並未改變capccity
    cout << vec.size() << endl; //10
    cout << vec.capacity() << endl; //128
    vector<int>(vec).swap(vec);
    cout << vec.size() << endl; //10
    cout << vec.capacity() << endl; //10
    vec.clear(); //clear並未真正釋放空間!!!
    cout << vec.size() << endl; //0
    cout << vec.capacity() << endl; //10
    vector<int> (vec).swap(vec); //這才真正釋放了空間!!
    cout << vec.size() << endl; //0
    cout << vec.capacity() << endl; //0
    return 0;
}


PS:C++11中已經實現了shink_to_fit函式。實現上述功能。



相關文章