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



描述

C++ 建構函式std::map::map() 透過初始化列表構造一個對映。

宣告

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

C++11

map (initializer_list<value_type> il,
     const key_compare& comp = key_compare(),
     const allocator_type& alloc = allocator_type());

引數

  • il − 初始化列表。

  • comp − 二元謂詞,它接受兩個鍵作為引數,如果第一個引數在第二個引數之前則返回 true,否則返回 false。預設情況下,它使用less<key_type>謂詞。

  • alloc − 分配器物件。

返回值

建構函式不返回值。

異常

此成員函式從不丟擲異常。

時間複雜度

線性,即 O(n)

示例

以下示例演示了 `std::map::map()` 建構函式的用法。

#include <iostream>
#include <map>

using namespace std;

int main(void) {
   /* Initializer_list constructor */
   map<char, int> m1 = {
            {'a', 1},
            {'b', 2},
            {'c', 3},
            {'d', 4},
            {'e', 5}
            };

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

   for (auto it = m1.begin(); it != m1.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
廣告