C++ unordered_set::clear() 函式



C++ 的std::unordered_set::clear()函式用於從 unordered_set 容器中刪除所有元素。如果當前 unordered_set 為空,則此函式不會進行任何更改,否則它將刪除 unordered_set 中的所有元素。呼叫此函式時,size() 函式將返回零。此函式的返回型別為 void,這意味著它不返回任何值。

語法

以下是 C++ std::unordered_set::clear() 函式的語法:

void clear();

引數

  • 它不接受任何引數。

返回值

此函式不返回任何值。

示例 1

讓我們看下面的例子,我們將使用 clear() 函式並觀察輸出。

#include<iostream>
#include<string>
#include<unordered_set>
using namespace std;

int main () {
   //create a unordered_set
   unordered_set<int> u_set = {1, 2, 3, 4, 5};
   cout<<"Contents of the u_set before the clear operation are: "<<endl;
   for(int n : u_set){
      cout<<n<<endl;
   }
   //using the clear() function
   u_set.clear();
   cout<<"Size of the u_set after the clear operation: "<<u_set.size();
}

輸出

如果我們執行以上程式碼,它將生成以下輸出:

Contents of the u_set before the clear operation are: 
5
4
3
2
1
Size of the u_set after the clear operation: 0

示例 2

考慮另一種情況,我們將對 char 型別的 unordered_set 使用 cler() 函式。

#include<iostream>
#include<string>
#include<unordered_set>
using namespace std;

int main () {
   //create a unordered_set
   unordered_set<char> char_set = {'A', 'B', 'C', 'D', 'E'};
   cout<<"Contents of the char_set before the clear operation are: "<<endl;
   for(char c : char_set){
      cout<<c<<endl;
   }
   //using the clear() function
   char_set.clear();
   cout<<"Size of the char_set after the clear operation: "<<char_set.size();
}

輸出

以下是以上程式碼的輸出:

Contents of the char_set before the clear operation are: 
E
D
C
B
A
Size of the char_set after the clear operation: 0

示例 3

以下是另一個在 string 型別的 unordered_set 上使用 clear() 函式的示例。

#include<iostream>
#include<string>
#include<unordered_set>
using namespace std;

int main () {
   //create a unordered_set
   unordered_set<string> str_set = {"Rahul", "Mukesh", "Dinesh", "Raja"};
   cout<<"Contents of the str_set before the clear operation are: "<<endl;
   for(string s : str_set){
      cout<<s<<endl;
   }
   //using the clear() function
   str_set.clear();
   cout<<"Size of the str_set after the clear operation: "<<str_set.size();
}

輸出

以上程式碼的輸出如下:

Contents of the str_set before the clear operation are: 
Dinesh
Mukesh
Raja
Rahul
Size of the str_set after the clear operation: 0
廣告

© . All rights reserved.