C++ STL 中的 map erase() 函式


在本文中,我們將討論 C++ STL 中 map::erase() 函式的工作原理、語法和示例。

什麼是 C++ STL 中的 Map?

Map 是關聯式容器,它可以方便地儲存由鍵值對組成的元素,並按照特定順序排列。在 map 容器中,資料內部始終透過其關聯的鍵進行排序。map 容器中的值可以透過其唯一的鍵訪問。

什麼是 map::erase()?

map::erase() 函式位於 <map&t; 標頭檔案中。此函式用於從與其關聯的 map 容器中移除一個或多個元素。我們也可以透過鍵來移除 map 中的元素。

此函式有效地將 map 容器的大小減少了從容器中移除的元素數量。

語法

map_name.erase(iterator pos);
map_name.erase(key_type &k);
map_name.erase(iterator start, iterator end);

引數

此函式接受以下

引數

  • pos − 一個迭代器,可以認為是要移除的元素的位置。
  • k − 我們想要從 map 容器中移除的鍵值。
  • start, end − 迭代器 ‘start’ 和 ‘end’ 用於指定要從 deque 容器中移除的範圍的起始位置和結束位置。

返回值

如果刪除成功,則函式返回 1,否則返回 0。

示例

輸入

map<char, int> newmap;
newmap[‘a’]
= 1;
newmap[‘b’] = 2;
newmap.erase(b);

輸出

a

示例

 線上演示

#include <bits/stdc++.h>
using namespace std;
int main() {
   map<int, int> TP_Map;
   TP_Map.emplace(3, 50);
   TP_Map.emplace(2, 30);
   TP_Map.emplace(1, 10);
   TP_Map.emplace(4, 70);
   cout<<"TP Map is : \n";
   cout << "MAP_KEY\tMAP_ELEMENT\n";
   for (auto i = TP_Map.begin(); i!= TP_Map.end(); i++) {
      cout << i->first << "\t" << i->second << endl;
   }
   //to erase the map values
   TP_Map.erase(1);
   TP_Map.erase(2);
   cout<<"\n\nAfter erasing the element: \n";
   cout << "MAP_KEY\tMAP_ELEMENT\n";
   for (auto i = TP_Map.begin(); i!= TP_Map.end(); i++) {
      cout << i->first << "\t" << i->second << endl;
   }
   return 0;
}

輸出

TP Map is:
MAP_KEY    MAP_ELEMENT
1             10
2             30
3             50
4             70
After erasing the element:
MAP_KEY    MAP_ELEMENT
3             50
4             70

示例

 線上演示

#include <bits/stdc++.h>
using namespace std;
int main() {
   map<int, int> TP_Map;
   TP_Map.insert({3, 50});
   TP_Map.insert({2, 30});
   TP_Map.insert({1, 10});
   TP_Map.insert({4, 70});
   cout<<"TP Map is : \n";
   cout << "MAP_KEY\tMAP_ELEMENT\n";
   for (auto i = TP_Map.begin(); i!= TP_Map.end(); i++) {
      cout << i->first << "\t" << i->second << endl;
   }
   //to erase the map values
   auto var = TP_Map.find(1);
   TP_Map.erase(var);
   auto var_1 = TP_Map.find(2);
   TP_Map.erase(var_1);
   cout<<"\n\nAfter erasing the element: \n";
   cout << "MAP_KEY\tMAP_ELEMENT\n";
   for (auto i = TP_Map.begin(); i!= TP_Map.end(); i++) {
      cout << i->first << "\t" << i->second << endl;
   }
   return 0;
}

輸出

TP Map is:
MAP_KEY    MAP_ELEMENT
1             10
2             30
3             50
4             70
After erasing the element:
MAP_KEY    MAP_ELEMENT
3             50
4             70

更新於:2020年4月15日

627 次瀏覽

啟動您的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.