deque::shrink_to_fit()是C++ STL中的內置函數,它會減小容器的容量以適應其大小,並破壞超出該容量的所有元素。此函數不會減小容器的尺寸。當為容器分配的內存超過了所需的內存量時,將使用此函數,然後此函數釋放已分配的額外內存量。
用法:
deque_name.shrink_to_fit()
參數:該函數不接受任何參數。
返回值:該函數不返回任何內容。
以下示例程序旨在說明上述函數:
Example-1
// C++ program to illustrate
// the deque::shrink_to_fit()
#include <bits/stdc++.h>
using namespace std;
int main()
{
// Initialized deque
deque<int> d(10);
for (int i = 0; i < 5; i++)
d[i] = i;
// Initial deque
cout << " Deque size initially:" << d.size();
cout << "\n Deque elements are:";
for (int i = 0; i < 10; i++)
cout << d[i] << " ";
// changes the size of the Deque
// but does not destroys the elements
d.resize(7);
cout << "\n Deque size after resize(7):"
<< d.size();
cout << "\n Deque elements after resize(7) are:";
for (int i = 0; i < 10; i++)
cout << d[i] << " ";
// Shrinks to the size
// till which elements are
// destroys the elements after 5
d.shrink_to_fit();
cout << "\n Deque size after shrink_to_fit():"
<< d.size();
cout << "\n Deque elements after shrink_to_fit() are:";
for (int i = 0; i < 10; i++)
cout << d[i] << " ";
return 0;
}
輸出:
Deque size initially:10 Deque elements are:0 1 2 3 4 0 0 0 0 0 Deque size after resize(7):7 Deque elements after resize(7) are:0 1 2 3 4 0 0 0 0 0 Deque size after shrink_to_fit():7 Deque elements after shrink_to_fit() are:0 1 2 3 4 0 0 0 0 0
示例2
// C++ program to illustrate
// the deque::shrink_to_fit()
#include <bits/stdc++.h>
using namespace std;
int main()
{
// creating a deque
deque<int> d(100);
cout << "Size of d is:" << d.size() << endl;
// resizing
d.resize(20);
cout << "Size of d after resize is:" << d.size() << endl;
d.shrink_to_fit();
return 0;
}
輸出:
Size of d is:100 Size of d after resize is:20
注意:shrink_to_fit()函數在容器大小不斷變化的向量中非常有用。
相關用法
- C++ deque::pop_front()、deque::pop_back()用法及代碼示例
- C++ deque::clear()、deque::erase()用法及代碼示例
- C++ deque::empty()、deque::size()用法及代碼示例
- C++ deque::front()、deque::back()用法及代碼示例
- C++ deque::emplace_front()、deque::emplace_back()用法及代碼示例
- C++ deque::at()、deque::swap()用法及代碼示例
- C++ deque cbegin()用法及代碼示例
- C++ deque get_allocator用法及代碼示例
- C++ deque crbegin用法及代碼示例
- C++ deque crend用法及代碼示例
- C++ deque emplace用法及代碼示例
- C++ deque::push_front()用法及代碼示例
- C++ deque::push_back()用法及代碼示例
注:本文由純淨天空篩選整理自ankit15697大神的英文原創作品 deque shrink_to_fit in C++ STL。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。