Map是字典一樣的數據結構。它是(鍵,值)對的關聯數組,其中每個唯一鍵僅與單個值相關聯。
map::clear()
clear()函數用於從Map容器中刪除所有元素,從而使其大小保持為0。
用法:
map1.clear() where map1 is the name of the map. 參數: No parameters are passed.
返回值:沒有
例子:
Input:map1 = { {1, "India"}, {2, "Nepal"}, {3, "Sri Lanka"}, {4, "Myanmar"} } map1.clear(); Output:map1 = {} Input:map2 = {} map2.clear(); Output:map2 = {}
// CPP program to illustrate
// Implementation of clear() function
#include <bits/stdc++.h>
using namespace std;
int main()
{
// Take any two maps
map<int, string> map1, map2;
// Inserting values
map1[1] = "India";
map1[2] = "Nepal";
map1[3] = "Sri Lanka";
map1[4] = "Myanmar";
// Print the size of map
cout<< "Map size before running function:\n";
cout << "map1 size = " << map1.size() << endl;
cout << "map2 size = " << map2.size() << endl;;
// Deleting the map elements
map1.clear();
map2.clear();
// Print the size of map
cout<< "Map size after running function:\n";
cout << "map1 size = " << map1.size() << endl;
cout << "map2 size = " << map2.size();
return 0;
}
輸出:
Map size before running function: map1 size = 4 map2 size = 0 Map size after running function: map1 size = 0 map2 size = 0
時間複雜度:線性即O(n)
相關用法
注:本文由純淨天空篩選整理自AKASH GUPTA 6大神的英文原創作品 map::clear() in C++ STL。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。