C++ Map 庫 - at() 函式



描述

C++ 函式std::map::at()返回與鍵關聯的對映值的引用k.

宣告

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

C++11

mapped_type& at (const key_type& k);
const mapped_type& at (const key_type& k) const;

引數

k − 訪問其對映值的鍵值。

返回值

如果物件是常量限定的,則方法返回對對映值的常量引用;否則返回非常量引用。

異常

如果鍵不存在,則方法返回out_of_range異常。

時間複雜度

對數,即 log(n)。

示例

以下示例演示了 std::map::at() 函式的使用方法。

#include <iostream>
#include <map>

using namespace std;

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

   cout << "Value of key m['a'] = " << m.at('a') << endl;

   try {
      m.at('z');
   } catch(const out_of_range &e) {
      cerr << "Exception at " << e.what() << endl;
   }

   return 0;
}

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

Value of key m['a'] = 1
Exception at map::at
map.htm
廣告
© . All rights reserved.