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



描述

C++ 函式std::map::erase() 從對映中移除元素範圍。

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

宣告

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

C++11

iterator erase (const_iterator first, const_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;

   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;

   cout << "After erase operation iterator points to = " << it->first << 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
After erase operation iterator points to = c
map.htm
廣告