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。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。