std::set<Key,Compare,Allocator>::count
From cppreference.com
| size_type count( const Key& key ) const; |
(1) | |
| template< class K > size_type count( const K& x ) const; |
(2) | (C++14以降) |
指定された引数と同等に比較される要素の数を返します。
1) 指定されたキー key を持つ要素の数を返します。このコンテナは重複を許可しないため、返り値は 1 または 0 のいずれかになります。
2) 値 x と同等に比較されるキーを持つ要素の数を返します。このオーバーロードは、修飾子付きID Compare::is_transparent が有効で型を示す場合にのみオーバーロード解決に参加します。これにより、
Key のインスタンスを構築せずにこの関数を呼び出すことができます。目次 |
[編集] パラメータ
| key | - | カウントする要素のキー値 |
| x | - | キーと比較するための代替値 |
[編集] 戻り値
キーが key または x と 同等 に比較される要素の数。オーバーロード (1) の場合、これは 1 または 0 のいずれかです。
[編集] 計算量
コンテナのサイズに対する対数時間と、見つかった要素の数に対する線形時間の合計。
注釈
| 機能テストマクロ | 値 | 規格 | 機能 |
|---|---|---|---|
__cpp_lib_generic_associative_lookup |
201304L |
(C++14) | 連想コンテナにおける異種比較検索; オーバーロード (2) |
[編集] 例
このコードを実行
#include <functional> #include <iostream> #include <set> struct S { int x; S(int i) : x{i} { std::cout << "S{" << i << "} "; } bool operator<(S const& s) const { return x < s.x; } }; struct R { int x; R(int i) : x{i} { std::cout << "R{" << i << "} "; } bool operator<(R const& r) const { return x < r.x; } }; bool operator<(R const& r, int i) { return r.x < i; } bool operator<(int i, R const& r) { return i < r.x; } int main() { std::set<int> t{3, 1, 4, 1, 5}; std::cout << t.count(1) << ", " << t.count(2) << ".\n"; std::set<S> s{3, 1, 4, 1, 5}; std::cout << ": " << s.count(1) << ", " << s.count(2) << ".\n"; // Two temporary objects S{1} and S{2} were created. // Comparison function object is defaulted std::less<S>, // which is not transparent (has no is_transparent member type). std::set<R, std::less<>> r{3, 1, 4, 1, 5}; std::cout << ": " << r.count(1) << ", " << r.count(2) << ".\n"; // C++14 heterogeneous lookup; temporary objects were not created. // Comparator std::less<void> has predefined is_transparent. }
出力
1, 0.
S{3} S{1} S{4} S{1} S{5} : S{1} 1, S{2} 0.
R{3} R{1} R{4} R{1} R{5} : 1, 0.[編集] 関連項目
| 特定のキーを持つ要素を検索する (公開メンバ関数) | |
| 特定のキーに一致する要素の範囲を返す (公開メンバ関数) |