etc

[C++] shrink_to_fit

조부장 2022. 11. 26. 00:36
constexpr void shrink_to_fit();  // since C++20
Requests the removal of unused capacity.

It is a non-binding request to reduce capacity() to size(). It depends on the implementation whether the request is fulfilled.

If reallocation occurs, all iterators, including the past the end iterator, and all references to the elements are invalidated. If no reallocation takes place, no iterators or references are invalidated.

동적배열 자료구조인 std::vector는 원소 추가나 resize를 호출할 때 capacity가 변경되는데요, 나중에 vector에 할당된 배열 용량을 줄이고 싶다면 swap 또는 shrink_to_fit 메소드를 사용해야 합니다

vector<int> v;
v.reserve(10000);
cout << v.capacity() << '\n';  // 10000

// ... vector 사용 완료

v.clear();
vector<int>(v).swap(v);  // before c++11
cout << v.capacity() << '\n';  // 0

C++11 이전엔 capacity를 줄이기 위해 위처럼 swap()을 사용했습니다.

shrink_to_fit은 C++11부터 추가된 메소드입니다. vector의 capacity를 size에 딱 맞게 만들도록 시도합니다.

주의할 점은 배열 내 원소 개수만큼 딱 맞춰서 새 배열을 만들어 전부 옮기는거라서, 필요한 만큼 resize 또는 clear를 호출해 사이즈를 줄여놓고 shrink를 해야 합니다. 예를 들어 원소가 100만개인 배열의 원소 수가 50만개가 되었다고 shrink_to_fit을 호출한다면 복사에 더 많은 시간이 걸려 비효율적일 겁니다.

또한 non-binding 메소드인데, 컴파일러에 따라 구현 방식이 달라질 수 있습니다. (블록단위로 shrink 하도록 최적화 하는 등)

 

shrink_to_fit은 string, deque, concurrent_vector 등의 컨테이너에서도 사용할 수 있습니다.

 

참고자료

https://en.cppreference.com/w/cpp/container/vector/shrink_to_fit

https://stackoverflow.com/questions/2664051/why-is-shrink-to-fit-non-binding

반응형