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



描述

C++ 函式std::map::emplace_hint() 使用提示作為元素的位置在對映中插入一個新元素。

宣告

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

C++11

template <class... Args>
iterator emplace_hint (const_iterator position, Args&&... args);

引數

  • position - 插入元素的位置提示。

  • args - 傳遞給構造新元素的引數。

返回值

返回指向新插入元素的迭代器。如果由於元素已存在而插入失敗,則返回指向現有元素的迭代器。

異常

此成員函式不丟擲異常。

時間複雜度

線性,即 O(n)

示例

以下示例顯示了 std::map::emplace_hint() 函式的用法。

#include <iostream>
#include <map>

using namespace std;

int main(void) {
   map<char, int> m = {
            {'b', 2},
            {'c', 3},
            {'d', 4},
            };

   m.emplace_hint(m.end(), 'e', 5);
   m.emplace_hint(m.begin(), 'a', 1);

   cout << "Map contains following elements" << endl;

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

   return 0;
}

讓我們編譯並執行以上程式,這將產生以下結果:

Map contains following elements
a = 1
b = 2
c = 3
d = 4
e = 5
map.htm
廣告