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


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

什麼是 C++ STL 中的 Map?

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

什麼是 map::emplace_hint()?

map::emplace_hint() 函式屬於…… header file. This function constructs and inserts an element with a hint into the associated map container.

如果要放置的元素的鍵是唯一的,則 emplace_hint() 會插入新元素。只有當不存在具有要插入的值的鍵的元素時,才會發生插入。

語法

map_name.emplace_hint(iterator it, Args&& args);

引數

此函式接受以下引數:

it - 可被視為要插入元素位置提示的迭代器。

args - 我們想要在“it”位置放置的引數或值。

返回值

如果插入成功,則函式返回指向已插入新元素的迭代器。否則,它返回指向容器中已存在的值的等效迭代器。

示例

輸入

map<char, int> newmap;
emplace_hint(newmap.end(), ‘a’, 1);

輸出

a

示例

 線上演示

#include <bits/stdc++.h>
using namespace std;
int main() {
   map<int, int> TP_Map;
   TP_Map.emplace_hint(TP_Map.begin(), 4, 50);
   TP_Map.emplace_hint(TP_Map.begin(), 2, 30);
   TP_Map.emplace_hint(TP_Map.begin(), 1, 10);
   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
4             50

更新於:2020年4月15日

123 次瀏覽

開啟你的職業生涯

完成課程獲得認證

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