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



描述

C++ 函数std::multimap::erase() 从位置移除多重映射中的单个元素。

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

声明

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

C++11

iterator erase (const_iterator position);

参数

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

返回值

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

异常

如果抛出异常,则对容器没有影响。

时间复杂度

对数,即 O(log n)

示例

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

#include <iostream>
#include <map>

using namespace std;

int main(void) {
   /* Multimap with duplicates */
   multimap<char, int> m {
            {'a', 1},
            {'a', 2},
            {'b', 3},
            {'c', 4},
            {'c', 5},
         };
   cout << "Multimap 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 << "Multimap 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 
        << " = " << it->second << endl;

   return 0;
}

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

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