deque :: shrink_to_fit()是C++ STL中的内置函数,可减少容器的容量以适应其大小,并破坏超出该容量的所有元素。此函数不会减小容器的尺寸。当为容器分配的内存超过了所需的内存量时,将使用此函数,然后此函数释放已分配的额外内存量。
句法:
deque_name.shrink_to_fit()
参数:该函数不接受任何参数。
返回值:该函数不返回任何内容。
下面的程序说明了上述函数:
示例1
// C++ program to illustrate
// the deque::shrink_to_fit()
#include
using namespace std;
int main()
{
// Initialized deque
deque 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
using namespace std;
int main()
{
// creating a deque
deque 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++基础课程为基础,以先进的C++和C++ STL课程基础加上STL。要完成从学习语言到DS Algo等的更多准备工作,请参阅“完整面试准备课程” 。