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
廣告