名稱空間
變體
操作

std::unordered_set<Key,Hash,KeyEqual,Allocator>::count

來自 cppreference.com
< cpp‎ | 容器‎ | 無序集合
 
 
 
 
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 相等(比較結果相等)的元素數量,由於此容器不允許重複,所以結果為 01
2) 返回鍵與指定引數 x 等價(比較結果等價)的元素數量。此過載僅在 Hash::is_transparentKeyEqual::is_transparent 有效且均表示一種型別時才參與過載決議。這假定此類 Hash 可以同時使用 KKey 型別呼叫,並且 KeyEqual 是透明的,這共同允許在不構造 Key 例項的情況下呼叫此函式。

目錄

[編輯] 引數

key - 要計數的元素的鍵值
x - 可與鍵透明比較的任何型別的值

[編輯] 返回值

1) 鍵為 key 的元素數量,即 10
2) 具有與 x 比較等價的鍵的元素的數量。

[編輯] 複雜度

平均情況下為常數時間,最壞情況下與容器大小成線性關係。

[編輯] 注意

特性測試 標準 特性
__cpp_lib_generic_unordered_lookup 201811L (C++20) 無序關聯容器中的異構比較查詢,過載 (2)

[編輯] 示例

#include <algorithm>
#include <iostream>
#include <unordered_set>
 
int main()
{
    std::unordered_set set{2, 7, 1, 8, 2, 8, 1, 8, 2, 8};
 
    std::cout << "The set is: ";
    for (int e : set)
        std::cout << e << ' ';
 
    const auto [min, max] = std::ranges::minmax(set);
 
    std::cout << "\nNumbers from " << min << " to " << max << " that are in the set: ";
    for (int i{min}; i <= max; ++i)
        if (set.count(i) == 1)
            std::cout << i << ' ';
    std::cout << '\n';
}

可能的輸出

The set is: 8 1 7 2
Numbers from 1 to 8 that are in the set: 1 2 7 8

[編輯] 參閱

查詢具有特定鍵的元素
(公共成員函式) [編輯]
(C++20)
檢查容器是否包含具有特定鍵的元素
(公共成員函式) [編輯]
返回與特定鍵匹配的元素範圍
(公共成員函式) [編輯]