C++ STL 中的 multiset clear() 函数


在本文中,我们将讨论 C++ STL 中 multiset::clear() 函数的工作原理、语法和示例。

什么是 C++ STL 中的 multiset?

Multiset 类似于 set 容器,这意味着它们像 set 一样以特定顺序存储键值对。

在 multiset 中,值与 set 一样被识别为键。multiset 和 set 之间的主要区别在于,set 的键是唯一的,这意味着没有两个键是相同的,而 multiset 可以包含相同的键值。

Multiset 键用于实现二叉搜索树。

什么是 multiset::clear()?

multiset::clear() 函数是 C++ STL 中的内置函数,定义在 <set> 头文件中。

它用于清除整个 multiset 容器。

clear() 删除 multiset 容器中的所有元素,并将 multiset 容器的大小设置为 0。

语法

ms_name.clear();

参数

该函数不接受任何参数。

返回值

此函数不返回任何值。

示例

Input: std::multiset<int> mymultiset = {1, 2, 2, 3, 4};
mymultiset.clear();
mymultiset.size();
Output: size of multiset = 0

示例

 在线演示

#include <bits/stdc++.h>
using namespace std;
int main() {
   int arr[] = {2, 4, 1, 3, 8, 5, 6};
   multiset<int> check(arr, arr + 7);
   cout<<"List is : ";
   for (auto i = check.begin(); i != check.end(); i++)
   cout << *i << " ";
   cout<<"\nList when clear() is applied: ";
   check.clear();
   for (auto i = check.begin(); i != check.end(); i++)
   cout << *i << " ";
   return 0;
}

输出

如果我们运行上面的代码,它将生成以下输出:

List is : 1 2 3 4 5 6 8
List when clear() is applied:

示例

 在线演示

#include <bits/stdc++.h>
using namespace std;
int main() {
   int arr[] = {2, 4, 1, 3, 8, 5, 6};
   multiset<int> check(arr, arr + 7);
   cout<<"List is : ";
   for (auto i = check.begin(); i != check.end(); i++)
   cout << *i << " ";
   cout<<"\nList when clear() is applied: ";
   if(check.empty()) {
      cout<<"\nList is null";
   } else {
      cout<<"\nList isn't null : ";
      for (auto i = check.begin(); i != check.end(); i++)
      cout << *i << " ";
      cout<<"\nsize is : "<<check.size();
   }
   int arr2[] = {2, 4, 1, 3, 8, 5, 6};
   multiset<int> check_2(arr2, arr2 + 7);
   cout<<"\nList when clear() is applied: ";
   check_2.clear();
   if(check_2.empty()) {
      cout<<"\nList is null";
      cout<<"\nsize is : "<<check_2.size();
   } else {
      cout<<"\nList isn't null : "<<check_2.size();
      for (auto i = check_2.begin(); i != check_2.end(); i++)
      cout << *i << " ";
      cout<<"\nsize is : "<<check_2.size();
   }
   return 0;
}

输出

如果我们运行上面的代码,它将生成以下输出:

List is : 1 2 3 4 5 6 8
List when clear() is applied:
List isn't null : 1 2 3 4 5 6 8
Size is : 7
List when clear() is applied:
List is null
size is : 0

更新于:2020年3月23日

202 次查看

启动您的职业生涯

通过完成课程获得认证

开始学习
广告
© . All rights reserved.