std::set<Key,Compare,Allocator>::count
來自 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.
[編輯] 參閱
查詢具有特定鍵的元素 (public member function) | |
返回與特定鍵匹配的元素範圍 (public member function) |