当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


C++ Map erase()用法及代码示例



描述

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

声明

以下是 std::multimap::erase() 函数形式 std::map 头的声明。

C++98

size_type erase (const key_type& k);

C++11

size_type erase (const key_type& k);

参数

k─ 要删除的元素的键。

返回值

返回移除的元素数。

异常

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

时间复杂度

对数,即 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},
         };
   size_t ret;

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

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

   cout << endl;

   ret = m.erase('a');

   cout << "Number of value removed are = " << ret << endl;

   cout << endl;

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

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

   return 0;
}

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

Multimap contains following elements before erase operation
a = 1
a = 2
b = 3
c = 4
c = 5

Number of value removed are = 2

Multimap contains following elements after erase operation
b = 3
c = 4
c = 5

相关用法


注:本文由纯净天空筛选整理自 C++ Map Library - erase() Function。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。