C++ STL 中的 map::clear()


在本文中,我們將討論 C++ STL 中 map::clear() 函式的工作原理、語法和示例。

什麼是 C++ STL 中的對映?

對映是一種關聯容器,它有助於以特定順序儲存由鍵值和對映值組合而成的元素。在對映容器中,資料在內部始終按其關聯鍵的幫助進行排序。透過其唯一鍵訪問對映容器中的值。

什麼是 map::clear()?

map::clear() 函式是 C++ STL 中的一個內建函式,在中定義 header file. clear() is used to remove all the content from the associated map container. This function removes all the values and makes the size of the container as 0.

語法

Map_name.clear();

引數

此函式不接受任何引數。

返回值

此函式不返回值

示例

輸入

map<char, int> newmap;
newmap[‘a’] = 1;
newmap[‘b’] = 2;
newmap[‘c’] = 3;
newmap.clear();

輸出

size of the map is: 0

示例

 即時演示

#include <bits/stdc++.h>
using namespace std;
int main() {
   map<int, string> TP_1, TP_2;
   //Insert values
   TP_1[1] = "Tutorials";
   TP_1[2] = "Point";
   TP_1[3] = "is an";
   TP_1[4] = "education portal";
   //size of map
   cout<< "Map size before clear() function: \n";
   cout << "Size of map1 = "<<TP_1.size() << endl;
   cout << "Size of map2 = "<<TP_2.size() << endl;
   //call clear() to delete the elements
   TP_1.clear();
   TP_2.clear();
   //now print the size of maps
   cout<< "Map size after applying clear() function: \n";
   cout << "Size of map1 = "<<TP_1.size() << endl;
   cout << "Size of map2 = "<<TP_2.size() << endl;
   return 0;
}

輸出

Map size before clear() function:
Size of map1 = 4
Size of map2 = 0
Map size after applying clear() function:
Size of map1 = 0
Size of map2 = 0

更新於: 15-4-2020

6 千次以上瀏覽量

開啟你的職業生涯

完成課程並獲得認證

立即開始
廣告
© . All rights reserved.