擦除函数用于从unordered_map中擦除元素。 unordered_map支持三种擦除功能:
- 通过迭代器擦除:它将迭代器作为参数,并删除该迭代器上存在的键和值。
句法unordered_map.erase(const iterator);
- 通过键擦除:以键为参数,并擦除键和值。
句法unordered_map.erase(const key);
- 按范围擦除:它使用两个迭代器作为参数,并擦除之间存在的所有键和值(包括起始迭代器和结束迭代器)。
句法:unordered_map.erase(const iteratorStart, const iteratorEnd);
// CPP program to demonstrate implementation of
// erase function in unordered_map.
#include
using namespace std;
int main()
{
unordered_map um;
// Adding some elements in the map.
um[12] = true;
um[4189] = false;
um[519] = true;
um[40] = false;
um[4991] = true;
cout << "Contents of the unordered_map : \n";
for (auto p : um)
cout << p.first << "==>" << p.second << "\n";
cout << "\n";
// erase by iterator
cout << "After erasing by Iterator : \n";
um.erase(um.begin());
for (auto p : um)
cout << p.first << "==>" << p.second << "\n";
cout << "\n";
// erase by value
cout << "After erasing by Key : \n";
um.erase(4189);
for (auto p : um)
cout << p.first << "==>" << p.second << "\n";
cout << "\n";
// erase by range
cout << "After erasing by Range : \n";
auto it = um.begin();
it++; // Returns iterator pointing to second element
um.erase(it, um.end());
for (auto p : um)
cout << p.first << "==>" << p.second << "\n";
cout << "\n";
return 0;
}
输出:
Contents of the unordered_map :
4991==>1
519==>1
40==>0
12==>1
4189==>0
After erasing by Iterator :
519==>1
40==>0
12==>1
4189==>0
After erasing by Key :
519==>1
40==>0
12==>1
After erasing by Range :
519==>1
要从最佳影片策划和实践问题去学习,检查了C++基础课程为基础,以先进的C++和C++ STL课程基础加上STL。要完成从学习语言到DS Algo等的更多准备工作,请参阅“完整面试准备课程” 。