vector는 erase()나 clear()를 쓰더라도 할당된 메모리를 직접적으로 해제하지 않는다.
오직 size()에만 영향을 줄 뿐 capacity()는 조절할 수 없다.
vector의 실제 할당된 메모리를 해제하거나 조정하기 위해서 swap(), shrink_to_fit() 함수를 활용해보자.
#include<iostream>
#include<vector>
using namespace std;
int main() {
vector<int> v(100, 0);
v.erase(v.begin() + 10);
v.erase(v.begin() + 20);
cout <<"before swap=>"<< "vector [v] size:" << v.size() << " " << "vector [v] capacity:" << v.capacity() << endl;
vector<int>(v).swap(v); // swap 사용
//위 코드와 같음
//vector<int> t(v);
//t.swap(v);
cout << "after swap=>"<<"vector [v] size:" << v.size() << " " << "vector [v] capacity:" << v.capacity() << endl;
v.erase(v.begin() + 30);
v.erase(v.begin() + 40);
cout << "before shrink_to_fit=>" << "vector [v] size:" << v.size() << " " << "vector [v] capacity:" << v.capacity() << endl;
v.shrink_to_fit(); // shrink_to_fit 사용
cout << "after shrink_to_fit=>" << "vector [v] size:" << v.size() << " " << "vector [v] capacity:" << v.capacity() << endl;
return 0;
}