多重對映::emplace() 在 C++ STL 中
在本文中,我們將討論 C++ STL 中 multimap::emplace() 函式的工作原理、語法和示例。
什麼是 C++ STL 中的 Multimap?
Multimap 是關聯容器,類似於 map 容器。它還有助於儲存由鍵值和已對映值的組合形成的元素,並按照特定順序。在 multimap 容器中,可以有多個元素與同一鍵關聯。資料始終藉助於其關聯鍵進行內部排序。
什麼是 multimap::emplace()?
multimap::emplace() 函式是 C++ STL 中的一個內建函式,在 <map> 標頭檔案中定義。emplace() 用於構造並插入一個新元素到 multimap 容器中。此函式有效地將容器的大小增加了 1。
此函式類似於 insert 函式,該函式複製或移動物件以將元素插入容器中。
語法
multimap_name.emplace(Args& val);
引數
該函式接受以下引數(多個):
val — 這是我們想要插入的元素。
返回值
此函式返回一個迭代器,表示置入/插入元素的位置。
輸入
std::multimap<char, int> odd, eve; odd.insert({‘a’, 1}); odd.emplace({‘b’, 3});
輸出
Odd: a:1 b:3
示例
#include <bits/stdc++.h> using namespace std; int main(){ //create the container multimap<int, int> mul; //insert using emplace mul.emplace(1, 10); mul.emplace(4, 20); mul.emplace(5, 30); mul.emplace(2, 40); mul.emplace(3, 50); mul.emplace(4, 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 10 2 40 3 50 4 20 4 60 5 30
廣告