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



描述

C++ 建構函式std::map::map() 使用範圍內的元素構造一個對映開始結束.

宣告

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

C++98

template <class InputIterator>
map (InputIterator first, InputIterator last,
     const key_compare& comp = key_compare(),
     const allocator_type& alloc = allocator_type());

C++11

template <class InputIterator>
map (InputIterator first, InputIterator last,
     const key_compare& comp = key_compare(),
     const allocator_type& = allocator_type());

引數

  • first - 輸入迭代器指向初始位置。

  • last - 輸入迭代器指向最終位置。

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

  • alloc - 分配器物件。

返回值

建構函式從不返回值。

異常

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

時間複雜度

線性,即 O(n)

示例

以下示例顯示了 std::map::map() 建構函式的使用。

#include <iostream>
#include <map>

using namespace std;

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

   map<char, int> m2(m1.begin(), m1.end());

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

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