C++ 對映庫 - emplace() 函式



描述

C++ 函式std::map::emplace() 透過插入新元素來擴充套件容器。

只有當鍵不存在時才會進行插入。

宣告

以下是來自 `std::map` 標頭檔案的 `std::map::emplace()` 函式的宣告。

C++11

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

引數

args − 傳遞給元素建構函式的引數。

返回值

返回一對:bool指示是否發生了插入,以及指向新插入元素的迭代器。

異常

如果任何操作丟擲異常,則此函式無效。

時間複雜度

對數,即 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
map.htm
廣告
© . All rights reserved.