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



描述

C++ 函数 std::map::erase() 从映射中移除单个元素。位置.

此成员函数将映射的大小减少一个。

声明

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

C++11

iterator erase (const_iterator position);

参数

position − 要移除的元素的迭代器。

返回值

返回最后一个被移除元素之后的迭代器。

异常

此成员函数不抛出异常。

时间复杂度

对数级,即 log(n)。

示例

以下示例演示了 std::map::erase() 函数的用法。

#include <iostream>
#include <map>

using namespace std;

int main(void) {
   /* Initializer_list constructor */
   map<char, int> m = {
            {'a', 1},
            {'b', 2},
            {'c', 3},
            {'d', 4},
            {'e', 5},
            };

   cout << "Map contains following elements before erase operation" << endl;

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

   auto it = m.erase(m.begin());

   cout << "Map contains following elements after erase operation" << endl;

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

   cout << "After erase operation iterator points to = " << it->first << endl;

   return 0;
}

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

Map contains following elements before erase operation
a = 1
b = 2
c = 3
d = 4
e = 5
Map contains following elements after erase operation
b = 2
c = 3
d = 4
e = 5
After erase operation iterator points to = b
map.htm
广告