C++ STL 中的 multimap::emplace_hint()
在本文中,我們將討論 C++ STL 中 multimap::emplace_hint() 函式的工作原理、語法和示例。
什麼是 C++ STL 中的 Multimap?
Multimap 是關聯容器,類似於 map 容器。它還有助於以特定順序儲存由鍵值和對映值組合而成的元素。在 multimap 容器中,可以有多個元素與同一個鍵相關聯。資料在內部始終藉助其關聯的鍵進行排序。
什麼是 multimap::emplace_hint()?
emplace_hint() 函式是 C++ STL 中的內建函式,它在 <map> 標頭檔案中定義。此函式在 multimap 容器中插入一個新元素,並帶有一個位置。在 emplace_hint() 中,我們傳遞帶有位置的元素,該位置充當提示。此函式類似於 emplace(),區別在於我們提供了一個位置提示來插入值。此函式還會將 multiset 容器的大小增加 1。
語法
multimap_name.emplace_hint(iterator pos, Args& val);
引數
該函式接受以下引數:
pos - 這是迭代器型別的引數,用於提供位置提示。
val - 這是我們要插入的元素。
返回值
此函式返回一個迭代器,指向放置/插入元素的位置。
輸入
std::multimap<char, int> odd, eve;
odd.insert({‘a’, 1});
odd.insert({‘b’, 3});
odd.insert({‘c’, 5});
odd.emplace_hint(odd.end(), {‘d’, 7});輸出
Odd: a:1 b:3 c:5 d:7
示例
Code:
#include <bits/stdc++.h>
using namespace std;
int main(){
//create the container
multimap<int, int> mul;
//insert using emplace
mul.emplace_hint(mul.begin(), 1, 10);
mul.emplace_hint(mul.begin(), 2, 20);
mul.emplace_hint(mul.begin(), 3, 30);
mul.emplace_hint(mul.begin(), 1, 40);
mul.emplace_hint(mul.begin(), 4, 50);
mul.emplace_hint(mul.begin(), 5, 60);
cout << "\nElements in multimap is : \n";
cout << "KEY\tELEMENT\n";
for (auto i = mul.begin(); i!= mul.end(); i++){
cout << i->first << "\t" << i->second << endl;
}
return 0;
}輸出
如果我們執行上述程式碼,它將生成以下輸出:
Elements in multimap is : KEY ELEMENT 1 40 1 10 2 20 3 30 4 50 5 60
廣告
資料結構
網路
關係資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP