C++ 無序對映庫 - equal() 函式



描述

C++ 函式std::unordered_map::equal() 返回與特定鍵匹配的元素範圍。

在無序對映容器中,鍵是唯一的,因此該範圍最多包含一個元素。如果k與容器中的任何鍵都不匹配,則返回的範圍的下限和上限都為結束。

宣告

以下是來自 std::unordered_map 標頭檔案的 std::unordered_map::equal() 函式的宣告。

C++11

pair<iterator,iterator> equal_range(const key_type& k);
pair<const_iterator,const_iterator> equal_range(const key_type& k) const;

引數

k - 要搜尋的鍵。

返回值

如果物件是常量限定的,則方法返回一對常量迭代器,否則返回一對非常量迭代器。

時間複雜度

平均情況下為常數,即 O(1)。

最壞情況下為線性,即 O(n)。

示例

以下示例顯示了 std::unordered_map::equal() 函式的使用方法。

#include <iostream>
#include <unordered_map>

using namespace std;

int main(void) {
   unordered_map<char, int> um = {
            {'a', 1},
            {'b', 2},
            {'c', 3},
            {'d', 4},
            {'e', 5}
            };

   auto ret = um.equal_range('b');

   cout << "Lower bound is " << ret.first->first 
       << " = "<< ret.first->second << endl;
   cout << "Upper bound is " << ret.second->first
       << " = " << ret.second->second << endl;

   return 0;
}

讓我們編譯並執行以上程式,這將產生以下結果:

Lower bound is b = 2
Upper bound is c = 3
unordered_map.htm
廣告