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



描述

C++ 函式 std::map::erase() 從對映中刪除一系列元素。

此成員函式減少對映的大小。

宣告

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

C++98

void erase (iterator first, iterator last);

引數

  • first − 輸入迭代器,指向範圍的初始位置。

  • last − 輸入迭代器,指向範圍的最終位置。

返回值

異常

此成員函式不丟擲異常。

時間複雜度

在之間距離的線性時間firstlast.

示例

以下示例演示了 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 befor erase operation" << endl;

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

   auto it = m.begin();
   ++it, ++it;

   m.erase(m.begin(), it);

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

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

   return 0;
}

讓我們編譯並執行上述程式,這將產生以下結果:

Map contains following elements befor erase operation
a = 1
b = 2
c = 3
d = 4
e = 5
Map contains following elements after erase operation
c = 3
d = 4
e = 5
map.htm
廣告