擦除函數用於擦除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 <bits/stdc++.h>
using namespace std;
int main()
{
unordered_map<int, bool> 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++ set::erase用法及代碼示例
- C++ multiset erase()用法及代碼示例
- C++ multimap::erase()用法及代碼示例
- C++ std::string::erase用法及代碼示例
- C++ map erase()用法及代碼示例
- C++ unordered_multimap erase用法及代碼示例
- C++ unordered_multiset erase()用法及代碼示例
- C++ vector erase()、clear()用法及代碼示例
- C++ list erase()用法及代碼示例
- C++ unordered_set erase()用法及代碼示例
- C++ deque::clear()、deque::erase()用法及代碼示例
注:本文由純淨天空篩選整理自DrRoot_大神的英文原創作品 unordered_map erase in C++ STL。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。