C++ Map 庫 - erase() 函式



描述

C++ 函式std::multimap::erase() 從 multimap 中移除指定範圍的元素。

此成員函式會減小 multimap 的大小。

宣告

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

C++11

iterator erase (const_iterator first, const_iterator last);

引數

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

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

返回值

返回一個迭代器,指向最後一個被移除元素的下一個位置。

異常

如果丟擲異常,則對容器沒有影響。

時間複雜度

firstlast.

示例

以下示例演示了 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},
         };
   cout << "Multimap 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.begin();
   ++it, ++it;

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

   cout << "Multimap 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 
        << " = " << it->second << endl;

   return 0;
}

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

Multimap contains following elements before erase operation
a = 1
a = 2
b = 3
c = 4
c = 5
Multimap contains following elements after erase operation
b = 3
c = 4
c = 5
After erase operation iterator points to b = 3
map.htm
廣告
© . All rights reserved.