📅  最后修改于: 2023-12-03 15:13:56.789000             🧑  作者: Mango
unordered_multimap是C++ STL中的一个容器,实现了无序的关联数组,即key-value的映射。clear()函数用于删除unordered_multimap中的所有元素。
void clear();
无。
无。
#include <iostream>
#include <unordered_map>
int main()
{
std::unordered_multimap<char, int> umap{{'a',1},{'b',2},{'b',3},{'c',4}};
std::cout << "Before clear(), umap contains " << umap.size() << " key-value pairs. \n";
std::cout << "Contents of umap: \n";
for(auto it = umap.begin(); it != umap.end(); ++it)
std::cout << it->first << " => " << it->second << std::endl;
umap.clear();
std::cout << "After clear(), umap contains " << umap.size() << " key-value pairs. \n";
return 0;
}
输出结果为:
Before clear(), umap contains 4 key-value pairs.
Contents of umap:
a => 1
c => 4
b => 2
b => 3
After clear(), umap contains 0 key-value pairs.
unordered_multimap clear()函数用于清空unordered_multimap中的所有元素,容器大小变成0。这是一个便捷函数,可以减少手写循环删除unordered_multimap元素的代码量。