The C++ std::deque::shrink_to_fit() function is used to reduce the capacity of a deque to fit its size, freeing unused memory. This function is non-binding, meaning it serves as a request to the implementation and may not always result in reduced capacity. It has no effect on the size or elements of the container.
SyntaxFollowing is the syntax for std::deque::shrink_to_fit() function.
void shrink_to_fit();Parameters
It does not accept any parameter.
Return valueThis function does not return anything.
ExceptionsThis function never throws exception.
Time complexityThe time complexity of this function is Constant i.e. O(1)
ExampleIn the following example, we are going to consider the basic usage of the shrink_to_fit() function.
#include <iostream> #include <deque> int main() { std::deque<int> a; for (int x = 0; x < 10; ++x) { a.push_back(x); } std::cout << "Deque size before shrink_to_fit(): " << a.size() << std::endl; a.shrink_to_fit(); std::cout << "Deque size after shrink_to_fit(): " << a.size() << std::endl; return 0; }Output
Output of the above code is as follows −
Deque size before shrink_to_fit(): 10 Deque size after shrink_to_fit(): 10Example
Consider the following example, where we are going to use the clear and shrink on the deque.
#include <iostream> #include <deque> int main() { std::deque<int> a; for (int x = 0; x < 5; ++x) { a.push_back(x); } a.clear(); a.shrink_to_fit(); std::cout << "Deque size after clear and shrink: " << a.size() << std::endl; return 0; }Output
Following is the output of the above code −
Deque size after clear and shrink: 0Example
In the following example, we are going to use the shrink after resizing.
#include <iostream> #include <deque> int main() { std::deque<int> a; for (int x = 0; x < 10; ++x) { a.push_back(x); } a.resize(5); a.shrink_to_fit(); std::cout << "Deque capacity after resizing and shrink: " << a.size() << std::endl; return 0; }Output
If we run the above code it will generate the following output −
Deque capacity after resizing and shrink: 5
deque.htm
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4