C++ unordered_map::clear() 函式



C++ 的unordered_map::clear()函式用於銷燬或清空unordered_map容器,方法是移除所有元素並將unordered_map的大小設定為零。

即使從unordered_map中移除了所有元素,我們也可以使用[]運算子向同一個unordered_map新增新元素。例如:unordered_map[1] = "tutorialspoint";

語法

以下是unordered_map::clear()函式的語法。

unordered_map.clear();

引數

此函式不接受任何引數。

返回值

此函式不返回任何值,因為使用clear()函式後unordered_map的大小為零。

示例1

在下面的示例中,讓我們演示clear()函式的使用,如下所示

#include <iostream>
#include <unordered_map>
using namespace std;
int main(void) {
   unordered_map<char, int> um = {
      {'a', 1},
      {'b', 2},
      {'c', 3},
      {'d', 4},
      {'e', 5}
   };
   cout << "Initial size of unordered map = " << um.size() << endl;
   um.clear();
   cout << "Size of unordered map after clear operation = " << um.size() << endl;
   return 0;
}

輸出

以上程式碼的輸出如下:

Initial size of unordered map = 5
Size of unordered map after clear operation = 0

示例2

下面的示例中,我們使用clear()函式清空unordered_map,然後向同一個unordered_map新增兩個元素,如下所示

#include <iostream>
#include <string>
#include <unordered_map>
using namespace std;
int main () {
   unordered_map<string,string> Umap = { {"Aman","Kumar"}, {"Vivek","Verma"}, {"Jhon","Satya"} };

   cout << "mymap contains:";
   for (auto& x: Umap)cout << " " << x.first << "=" << x.second;
   cout << endl;
    
   //removing all the element from the map.
   Umap.clear();
    
   //adding two element from the map
   Umap["TutorialsPoint"]="Tutorix";
   Umap["Location"]="Hyderabad";
   cout << "mymap contains:";
   for (auto& x: Umap) cout << " " << x.first << "=" << x.second;
      cout << endl;
   return 0;
}

輸出

執行後,我們得到以下輸出:

mymap contains: Jhon=Satya Vivek=Verma Aman=Kumar
mymap contains: Location=Hyderabad TutorialsPoint=Tutorix

示例3

讓我們看看下面的例子,我們顯示使用clear()函式之前unordered_map的元素,然後顯示unordered_map的大小,如下所示

#include <iostream>
#include <string>
#include <unordered_map>
using namespace std;
int main () {
   unordered_map<int, string> Umap;
   Umap[1] = "tutorialspoint";
   Umap[2] = "Hyderabad India";
   Umap[3] = "Tutorix";
   Umap[4] = "Noida India";
   cout<<"Before use of clear() functon";
   for (auto& x: Umap) cout << "\n" << x.first << "=" << x.second;
      cout << endl;
    
   Umap.clear();
   cout<<"After use of clear() function \n";
   cout <<Umap.size();
   return 0;
}

輸出

以上程式碼的輸出如下:

Before use of clear() functon
4=Noida India
3=Tutorix
2=Hyderabad India
1=tutorialspoint
After use of clear() function 
0
廣告