名稱空間
變體
操作

std::map<Key,T,Compare,Allocator>::equal_range

來自 cppreference.com
< cpp‎ | 容器‎ | map
 
 
 
 
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比較的替代值

[edit] 返回值

std::pair 包含一對迭代器,定義了所需範圍:第一個指向不小於 key 的第一個元素,第二個指向大於 key 的第一個元素。

如果沒有元素不小於 key,則返回 past-the-end(參見 end())迭代器作為第一個元素。類似地,如果沒有元素大於 key,則返回 past-the-end 迭代器作為第二個元素。

[編輯] 複雜度

容器大小的對數級別。

注意

特性測試 標準 特性
__cpp_lib_generic_associative_lookup 201304L (C++14) 針對過載 (3,4)關聯容器中的異構比較查詢

[編輯] 示例

#include <iostream>
#include <map>
 
int main()
{
    const std::map<int, const char*> m
    {
        {0, "zero"},
        {1, "one"},
        {2, "two"}
    };
 
    auto p = m.equal_range(1);
    for (auto& q = p.first; q != p.second; ++q)
        std::cout << "m[" << q->first << "] = " << q->second << '\n';
 
    if (p.second == m.find(2))
        std::cout << "end of equal_range (p.second) is one-past p.first\n";
    else
        std::cout << "unexpected; p.second expected to be one-past p.first\n";
 
    auto pp = m.equal_range(-1);
    if (pp.first == m.begin())
        std::cout << "pp.first is iterator to first not-less than -1\n";
    else
        std::cout << "unexpected pp.first\n";
 
    if (pp.second == m.begin())
        std::cout << "pp.second is iterator to first element greater-than -1\n";
    else
        std::cout << "unexpected pp.second\n";
 
    auto ppp = m.equal_range(3);
    if (ppp.first == m.end())
        std::cout << "ppp.first is iterator to first not-less than 3\n";
    else
        std::cout << "unexpected ppp.first\n";
 
    if (ppp.second == m.end())
        std::cout << "ppp.second is iterator to first element greater-than 3\n";
    else
        std::cout << "unexpected ppp.second\n";
}

輸出

m[1] = one
end of equal_range (p.second) is one-past p.first
pp.first is iterator to first not-less than -1
pp.second is iterator to first element greater-than -1
ppp.first is iterator to first not-less than 3
ppp.second is iterator to first element greater-than 3

[編輯] 另請參閱

查詢具有特定鍵的元素
(公共成員函式) [編輯]
(C++20)
檢查容器是否包含具有特定鍵的元素
(公共成員函式) [編輯]
返回匹配特定鍵的元素數量
(公共成員函式) [編輯]
返回指向第一個大於給定鍵的元素的迭代器
(公共成員函式) [編輯]
返回指向第一個不小於給定鍵的元素的迭代器
(公共成員函式) [編輯]
返回與特定鍵匹配的元素範圍
(函式模板) [編輯]