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



描述

C++ 函式 std::map::count() 返回與鍵關聯的對映值的個數k.

由於此容器不允許重複值,因此值始終為 0 或 1。

宣告

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

C++98

size_type count (const key_type& k) const;

引數

k - 搜尋操作的鍵。

返回值

如果容器具有與鍵關聯的值,則返回 1k否則返回 0。

異常

此成員函式不丟擲異常。

時間複雜度

對數,即 log(n)。

示例

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

#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},
            };

   if (m.count('a') == 1) {
      cout << "m['a'] = " << m.at('a') << endl;
   }

   if (m.count('z') == 0) {
      cout << "Value not present for key m['z']" << endl;
   }

   return 0;
}

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

m['a'] = 1
Value not present for key m['z']
map.htm
廣告

© . All rights reserved.