C++ 對映庫 - erase() 函式



描述

C++ 函式std::multimap::erase() 刪除與鍵關聯的對映值k.

宣告

以下是來自 std::map 標頭檔案的 std::multimap::erase() 函式宣告。

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
map.htm
廣告