std::set<Key,Compare,Allocator>::equal_range
來自 cppreference.com
std::pair<iterator, iterator> equal_range( const Key& key ); |
(1) | |
std::pair<const_iterator, const_iterator> equal_range( const Key& key ) const; |
(2) | |
template< class K > std::pair<iterator, iterator> equal_range( const K& x ); |
(3) | (C++14 起) |
template< class K > std::pair<const_iterator, const_iterator> equal_range( const K& x ) const; |
(4) | (C++14 起) |
返回一個範圍,其中包含容器中所有具有給定鍵的元素。該範圍由兩個迭代器定義,一個指向不小於 key 的第一個元素,另一個指向大於 key 的第一個元素。或者,第一個迭代器可以透過 lower_bound() 獲取,第二個迭代器可以透過 upper_bound() 獲取。
1,2) 將鍵與 key 進行比較。
3,4) 將鍵與值 x 進行比較。此過載僅在限定 ID Compare::is_transparent 有效並表示一種型別時才參與過載解析。它允許在不構造
Key
例項的情況下呼叫此函式。目錄 |
[編輯] 引數
key | - | 用於比較元素的鍵值 |
x | - | 可與Key 比較的替代值 |
[編輯] 返回值
一個 std::pair,包含一對定義所需範圍的迭代器:第一個迭代器指向不小於 key 的第一個元素,第二個迭代器指向大於 key 的第一個元素。
如果沒有不小於 key 的元素,則返回末尾(見 end())迭代器作為第一個元素。類似地,如果沒有大於 key 的元素,則返回末尾迭代器作為第二個元素。
[編輯] 複雜度
容器大小的對數級別。
注意
特性測試宏 | 值 | 標準 | 特性 |
---|---|---|---|
__cpp_lib_generic_associative_lookup |
201304L |
(C++14) | 針對過載 (3,4),關聯容器中的異構比較查詢 |
[編輯] 示例
執行此程式碼
#include <set> #include <functional> #include <print> #include <ranges> #include <string> #include <string_view> #include <tuple> struct Names { std::string forename, surname; friend auto operator<(const Names& lhs, const Names& rhs) { return std::tie(lhs.surname, lhs.forename) < std::tie(rhs.surname, rhs.forename); } }; struct SurnameCompare { std::string_view surname; friend bool operator<(const Names& lhs, const SurnameCompare& rhs) { return lhs.surname < rhs.surname; } friend bool operator<(const SurnameCompare& lhs, const Names& rhs) { return lhs.surname < rhs.surname; } }; std::set<Names, std::less<>> characters { {"Homer", "Simpson"}, {"Marge", "Simpson"}, {"Lisa", "Simpson"}, {"Ned", "Flanders"}, {"Joe", "Quimby"} }; void print_unique(const Names& names) { auto [begin, end] = characters.equal_range(names); std::print( "Found {} characters with name \"{} {}\"\n", std::distance(begin, end), names.forename, names.surname ); } void print_by_surname(std::string_view surname) { auto [begin, end] = characters.equal_range(SurnameCompare{surname}); std::print("Found {} characters with surname \"{}\":\n", std::distance(begin, end), surname); for (const Names& names : std::ranges::subrange(begin, end)) std::print(" {} {}\n", names.forename, names.surname); } int main() { print_unique({"Maude", "Flanders"}); print_unique({"Lisa", "Simpson"}); print_by_surname("Simpson"); }
輸出
Found 0 characters with name "Maude Flanders" Found 1 characters with name "Lisa Simpson" Found 3 characters with surname "Simpson": Homer Simpson Lisa Simpson Marge Simpson
[編輯] 另請參閱
查詢具有特定鍵的元素 (公共成員函式) | |
(C++20) |
檢查容器是否包含具有特定鍵的元素 (公共成員函式) |
返回匹配特定鍵的元素數量 (公共成員函式) | |
返回指向第一個大於給定鍵的元素的迭代器 (公共成員函式) | |
返回指向第一個不小於給定鍵的元素的迭代器 (公共成員函式) | |
返回與特定鍵匹配的元素範圍 (函式模板) |