unordered_map::clear()函數用於從容器中刪除所有元素。當此函數應用於unordered_map時,其大小變為零。
用法:
unordered_map_name.clear()
參數:該函數不接受任何參數
返回類型:此函數不返回任何內容。
Examples:
Input: ump = { {1, 2}, {3, 4}, {5, 6}, {7, 8}}
ump.clear();
Output: ump = { };
// CPP program to illustrate
// Implementation of unordered_map clear() function
#include <bits/stdc++.h>
using namespace std;
int main()
{
// Take any two unordered_map
unordered_map<int, int> ump1, ump2;
// Inserting values
ump1[1] = 2;
ump1[3] = 4;
ump1[5] = 6;
ump1[7] = 8;
// Print the size of container
cout << "Unordered_map size before calling clear function:\n";
cout << "ump1 size = " << ump1.size() << endl;
cout << "ump2 size = " << ump2.size() << endl;
// Deleting the elements
ump1.clear();
ump2.clear();
// Print the size of container
cout << "Unordered_map size after calling clear function:\n";
cout << "ump1 size = " << ump1.size() << endl;
cout << "ump2 size = " << ump2.size() << endl;
return 0;
}
輸出:
Unordered_map size before calling clear function: ump1 size = 4 ump2 size = 0 Unordered_map size after calling clear function: ump1 size = 0 ump2 size = 0
有什麽用途?
當我們希望刪除舊元素並從新開始時,尤其是在循環中,使用clear。我們可以通過創建新的映射來實現相同的函數,但是清除相同的映射在性能上更好,因為我們不必創建新的對象。
相關用法
- C++ set::clear用法及代碼示例
- C++ map::clear()用法及代碼示例
- C++ std::string::clear用法及代碼示例
- C++ list::clear()用法及代碼示例
- C++ unordered_multimap clear()用法及代碼示例
- C++ vector erase()、clear()用法及代碼示例
- C++ unoredered_set clear()用法及代碼示例
- PHP Imagick clear()用法及代碼示例
- C++ multiset clear()用法及代碼示例
- C++ unordered_multiset clear()用法及代碼示例
注:本文由純淨天空篩選整理自ankit15697大神的英文原創作品 unordered_map clear in C++ STL。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。