std::unordered_map<Key,T,Hash,KeyEqual,Allocator>::count
來自 cppreference.com
| size_type count( const Key& key ) const; |
(1) | (C++11 起) |
| template< class K > size_type count( const K& x ) const; |
(2) | (C++20 起) |
1) 返回與指定引數 key 比較相等的元素的數量,由於此容器不允許重複,該數量為 0 或 1。
2) 返回與指定引數 x 比較等價的元素的數量。此過載僅在 Hash::is_transparent 和 KeyEqual::is_transparent 有效且各自表示一個型別時才參與過載決議。這假設此類
Hash 可以使用 K 和 Key 型別呼叫,並且 KeyEqual 是透明的,這共同允許在不構造 Key 例項的情況下呼叫此函式。目錄 |
[編輯] 引數
| key | - | 要計數的元素的鍵值 |
| x | - | 可與鍵透明比較的任何型別的值 |
[編輯] 返回值
1) 鍵為 key 的元素的數量,即 1 或 0。
2) 具有與 x 比較等價的鍵的元素的數量。
[編輯] 複雜度
平均情況下為常數時間,最壞情況下與容器大小成線性關係。
[編輯] 注意
| 特性測試宏 | 值 | 標準 | 特性 |
|---|---|---|---|
__cpp_lib_generic_unordered_lookup |
201811L |
(C++20) | 無序關聯容器中的異構比較查詢,過載 (2) |
[編輯] 示例
執行此程式碼
#include <iostream> #include <string> #include <unordered_map> int main() { std::unordered_map<int, std::string> dict = { {1, "one"}, {6, "six"}, {3, "three"} }; dict.insert({4, "four"}); dict.insert({5, "five"}); dict.insert({6, "six"}); std::cout << "dict: { "; for (auto const& [key, value] : dict) std::cout << '[' << key << "]=" << value << ' '; std::cout << "}\n\n"; for (int i{1}; i != 8; ++i) std::cout << "dict.count(" << i << ") = " << dict.count(i) << '\n'; }
可能的輸出
dict: { [5]=five [4]=four [1]=one [6]=six [3]=three }
dict.count(1) = 1
dict.count(2) = 0
dict.count(3) = 1
dict.count(4) = 1
dict.count(5) = 1
dict.count(6) = 1
dict.count(7) = 0[編輯] 參閱
| 查詢具有特定鍵的元素 (public member function) | |
| (C++20) |
檢查容器是否包含具有特定鍵的元素 (public member function) |
| 返回與特定鍵匹配的元素範圍 (public member function) |