當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


C++ Map emplace()用法及代碼示例


描述

C++ 函數std::map::emplace()通過插入新元素擴展容器。

僅當 key 不存在時才會插入。

聲明

以下是 std::map::emplace() 函數形式 std::map 頭的聲明。

C++11

template <class... Args>
pair<iterator,bool> emplace (Args&&... args);

參數

args- 轉發給元素的構造函數的參數。

返回值

返回一對由布爾指示是否發生插入並返回一個迭代器到新插入的元素。

異常

如果任何操作拋出異常,則此函數無效。

時間複雜度

對數,即 log(n)

示例

下麵的例子展示了 std::map::emplace() 函數的用法。

#include <iostream>
#include <map>

using namespace std;

int main(void) {
   /* Initializer_list constructor */
   map<char, int> m;

   m.emplace('a', 1);
   m.emplace('b', 2);
   m.emplace('c', 3);
   m.emplace('d', 4);
   m.emplace('e', 5);

   cout << "Map contains following elements in reverse order" << endl;

   for (auto it = m.begin(); it != m.end(); ++it)
      cout << it->first << " = " << it->second << endl;

   return 0;
}

讓我們編譯並運行上麵的程序,這將產生以下結果——

Map contains following elements in reverse order
a = 1
b = 2
c = 3
d = 4
e = 5

相關用法


注:本文由純淨天空篩選整理自 C++ Map Library - emplace() Function。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。