C++ STL 中的 map insert()


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

什麼是 C++ STL 中的 Map?

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

什麼是 map::insert()?

map::insert() 函式是 C++ STL 中的內建函式,定義在…… header file. insert() is used to insert new values to the map container and increases the size of container by the number of elements inserted.

由於 map 容器中的鍵是唯一的,插入操作會檢查每個要插入的元素的鍵是否已存在於容器中,如果已存在,則不會插入該元素。

此外,map 容器透過其各自的鍵按升序維護所有元素。因此,每當我們插入一個元素時,它都會根據其鍵進入其相應的位置。

語法

1. Map_name.insert({key& k, value_type& val});
or
2. Map_name.insert(iterator& it, {key& k, value_type& val});
or
3. Map_name.insert(iterator& position1, iterator& position2);

引數

此函式接受以下引數:

  • k − 這是與元素關聯的鍵。該函式檢查鍵是否已存在於容器中,如果已存在,則不會插入元素。

  • val − 要插入的值。

  • it − 值的迭代器型別,用於指定要插入元素的位置。

  • position1, position2 − position1 是起始位置,position2 是結束位置。當我們想要插入一系列元素時,可以使用我們要插入的多個元素的範圍。

返回值

此函式返回指向 map 容器中新插入元素的迭代器。

示例

輸入

map<char, int> newmap;
newmap[‘a’] = 1;
newmap[‘b’] = 2;
newmap[‘c’] = 3;
newmap.insert({d, 50});

輸出

a:1
b:2
c:3
d:50

示例

線上演示

#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;
   }
   return 0;
}

輸出

TP Map is:
MAP_KEY    MAP_ELEMENT
1          10
2          30
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});
   auto i = TP_Map.find(4);
   TP_Map.insert(i, { 5, 80 });
   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;
   }
   return 0;
}

輸出

TP Map is:
MAP_KEY    MAP_ELEMENT
1             10
2             30
3             50
4             70
5             80

更新於:2020年4月15日

9000+ 次瀏覽

啟動您的職業生涯

完成課程,獲得認證

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