C++ .shrink_to_fit()

jjw's avatar
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.

  • 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

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 integers
std::deque<int> numbers;
// Add elements to the deque
for (int i = 0; i < 100; ++i) {
numbers.push_back(i);
}
std::cout << "Size: " << numbers.size() << std::endl;
// Remove many elements
while (numbers.size() > 10) {
numbers.pop_back();
}
std::cout << "Size after removal: " << numbers.size() << std::endl;
// Request to shrink capacity
numbers.shrink_to_fit();
// Display the elements
std::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: 100
Size after removal: 10
Final 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:

Code
Output
Loading...

All contributors

Contribute to 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