C++ 无序映射库 - erase() 函数



描述

C++ 函数 std::unordered_map::erase() 删除与键关联的映射值k.

声明

以下是来自 std::unordered_map 头文件的 std::unordered_map::erase() 函数声明。

C++11

size_type erase(const key_type& k);

参数

k − 要删除的元素的键。

返回值

返回删除的元素数量。

时间复杂度

常数,即 O(1)

示例

以下示例显示了 std::unordered_map::erase() 函数的使用方法。

#include <iostream>
#include <unordered_map>

using namespace std;

int main(void) {
   unordered_map<char, int> um = {
            {'a', 1},
            {'b', 2},
            {'c', 3},
            {'d', 4},
            {'e', 5}
            };

   cout << "Unordered map contains following elements before erase operation" << endl;

   for (auto it = um.begin(); it != um.end(); ++it)
      cout << it->first << " = " << it->second << endl;

   um.erase('a');

   cout << endl;
   cout << "Unordered map contains following elements after erase operation" << endl;

   for (auto it = um.begin(); it != um.end(); ++it)
      cout << it->first << " = " << it->second << endl;

   return 0;
}

让我们编译并运行上述程序,这将产生以下结果:

Unordered map contains following elements before erase operation
e = 5
a = 1
b = 2
c = 3
d = 4
Unordered map contains following elements after erase operation
e = 5
b = 2
c = 3
d = 4
unordered_map.htm
广告