Namespaces
Variants

std::unordered_map<Key,T,Hash,KeyEqual,Allocator>:: count

From cppreference.net

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 KeyEqual が両方とも transparent である場合にのみオーバーロード解決に参加します。これは、そのような Hash K 型と Key 型の両方で呼び出し可能であり、かつ KeyEqual がtransparentであることを前提としており、これらにより 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)