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.