C++ .shrink_to_fit()
Published Oct 28, 2025
Contribute to Docs
In C++, the .shrink_to_fit() method requests the deque to reduce its capacity to match its size. This can help free up unused memory, but does not guarantee that the container will actually shrink. The implementation may choose to ignore this request.
Syntax
dequeName.shrink_to_fit();
Parameters:
This method does not take any parameters.
Return value:
This method does not return a value, it simply requests that the deque reduce its capacity.
Example
The example below showcases the use of the .shrink_to_fit() method:
#include <iostream>#include <deque>int main() {// Create a deque of integersstd::deque<int> numbers;// Add elements to the dequefor (int i = 0; i < 100; ++i) {numbers.push_back(i);}std::cout << "Size: " << numbers.size() << std::endl;// Remove many elementswhile (numbers.size() > 10) {numbers.pop_back();}std::cout << "Size after removal: " << numbers.size() << std::endl;// Request to shrink capacitynumbers.shrink_to_fit();// Display the elementsstd::cout << "Final deque contents: ";for (int num : numbers) {std::cout << num << " ";}std::cout << std::endl;return 0;}
The above code generates the following output:
Size: 100Size after removal: 10Final deque contents: 0 1 2 3 4 5 6 7 8 9
Codebyte Example
The following codebyte demonstrates the use of the .shrink_to_fit() method after removing elements from the deque:
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn C++ on Codecademy
- Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
- Includes 6 Courses
- With Professional Certification
- Beginner Friendly.75 hours
- Learn C++ — a versatile programming language that’s important for developing software, games, databases, and more.
- Beginner Friendly.11 hours