C++ map clear() 函数

2024年8月30日 | 阅读4分钟

C++ map 的 clear() 函数用于移除 map 容器中的所有元素。它会清空 map 并将其大小设置为 0。

语法

参数

返回值

示例 1

让我们看一个简单的例子,计算 clear 操作前后 map 的大小。

输出

Initial size of map before clear operation = 5
Size of map after clear opearation = 0

在上面的例子中,一个 map 被初始化了 5 个元素。因此,map 的大小是 5,但在 clear 操作之后,大小变为 0。

示例 2

让我们看一个简单的例子来清除 map 中的元素。

输出

mymap contains:
1 : Nikita
2 : Deep
3 : Ashish

mymap contains:
4 : Rajni
5 : Sunil 

在上面的例子中,清除 map 后,我们可以无需初始化就添加新元素。

示例 3

让我们看一个简单的例子来清除 map 中的元素。

输出

m1 group has following members:
1 : Nikita
2 : Deep
3 : Ashish
m2 group has following members:
1 : Nidhi
2 : Priya
3 : Gitanjali
m3 group has following members:
1 : Rakesh
2 : Fruti
3 : Kamlesh

Which group do you want to delete?
 1. m1
 2. m2
 3. m3
 Please enter your choice: 2

Group m2 has been cleared.

在上面的例子中,有三组 map,根据用户的选择,其中一组被删除。

示例 4

让我们看一个简单的例子

输出

1. 
Fruit bucket has following fruits = 
Apple : 190
Banana : 40
Orange : 120

Do you want to clear your fruit bucket?
Press 1 for Yes and 0 for No: 0
3 fruits in bucket



2. 
Fruit bucket has following fruits = 
Apple : 190
Banana : 40
Orange : 120

Do you want to clear your fruit bucket?
Press 1 for Yes and 0 for No: 1
0 fruits in bucket

在上面的例子中,一个水果 map 被初始化了三种水果。程序会询问是否要清除 map,如果您输入 0,则水果篮中有 3 个元素;如果您输入 1,则会清除水果 map,其大小变为 0。

下一个主题C++ Map