在本文中,我們將討論 deque::shrink_to_fit() 函數在 C++ STL 中的工作、語法和示例。
什麽是德克?
Deque 是雙端隊列,是序列容器,提供兩端擴展和收縮的函數。隊列數據結構允許用戶僅在 END 插入數據並從 FRONT 刪除數據。讓我們以公交車站的隊列進行類比,其中人隻能從 END 插入隊列,站在 FRONT 的人最先被移除,而在雙端隊列中,可以在兩個隊列中插入和刪除數據結束。
什麽是雙端隊列::shrink_to_fit()?
deque::shrink_to_fit() 是 C++ STL 中的內置函數,它在 <deque> 頭文件中聲明。 deque::shrink_to_fit() 將 deque 容器的容量縮小到指定的適合大小並刪除所有超出適合的元素。當我們遇到大小問題或容器超出指定大小時,此函數非常有用。
用法
mydeque.shrink_to_fit();
該函數不需要參數。
返回值
此函數不返回任何內容。
示例
Input:deque<int> mydeque = {10, 20 30, 40, 0, 0, 0};
mydeque.shrink_to_fit();
Output:
Size of the mydeque = 40
示例
#include <bits/stdc++.h>
using namespace std;
int main(){
deque<int> Deque(50);
cout<<"Initial size of Deque is:" << Deque.size();
Deque.resize(40);
cout<<"\nDeque size after resizing it:" << Deque.size() << endl;
Deque.shrink_to_fit();
return 0;
}
輸出
如果我們運行上麵的代碼,它將生成以下輸出 -
Initial size of Deque is:50 Deque size after resizing it:4
示例
#include <bits/stdc++.h>
using namespace std;
int main(){
deque<int> Deque(10);
for (int i = 0; i <= 5; i++)
Deque[i] = i;
cout<<"Initial size of Deque is:" << Deque.size();
cout<<"\n Deque elements are:";
for (int i = 0; i <= 7; i++)
cout << Deque[i] << " ";
Deque.resize(10);
cout << "\n After resizing deque size is:"<<Deque.size();
cout << "\n Deque elements are:";
for (int i = 0; i < 10; i++)
cout << Deque[i] << " ";
Deque.shrink_to_fit();
return 0;
}
輸出
如果我們運行上麵的代碼,它將生成以下輸出 -
Deque elements are:0 1 2 3 4 5 0 0 After resizing deque size is:10 Deque elements are:0 1 2 3 4 5 0 0 0 0
相關用法
- C++ Deque shrink_to_fit()用法及代碼示例
- C++ Deque shrink()用法及代碼示例
- C++ Deque size()用法及代碼示例
- C++ Deque swap()用法及代碼示例
- C++ Deque erase()用法及代碼示例
- C++ Deque push_back()用法及代碼示例
- C++ Deque max_size()用法及代碼示例
- C++ Deque back()用法及代碼示例
- C++ Deque empty()用法及代碼示例
- C++ Deque clear()用法及代碼示例
- C++ Deque deque()用法及代碼示例
- C++ Deque pop_back()用法及代碼示例
- C++ Deque emplace_back()用法及代碼示例
- C++ Deque end()用法及代碼示例
- C++ Deque cbegin()用法及代碼示例
- C++ Deque front()用法及代碼示例
- C++ Deque resize()用法及代碼示例
- C++ Deque at()用法及代碼示例
- C++ Deque rbegin()用法及代碼示例
- C++ Deque emplace()用法及代碼示例
注:本文由純淨天空篩選整理自Sunidhi Bansal大神的英文原創作品 Deque shrink_to_fit in C++ STL。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。