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


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


描述

C++ 構造函數std::map::map()從初始化列表構造映射。

聲明

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

C++11

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

參數

  • il− 初始化列表。

  • comp- 一個二元謂詞,它接受兩個關鍵參數,如果第一個參數在第二個參數之前,則返回真,否則返回假。默認情況下它使用少<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

相關用法


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