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
广告