C++ STL 中的 multiset equal_range() 函式


在本文中,我們將討論 C++ STL 中 multiset::equal_range() 函式的工作原理、語法和示例。

什麼是 C++ STL 中的 multiset?

Multiset 與 set 容器類似,這意味著它們以鍵的形式儲存值,就像 set 一樣,並以特定的順序儲存。

在 multiset 中,值與 set 一樣被識別為鍵。multiset 和 set 之間的主要區別在於,set 具有不同的鍵,這意味著沒有兩個鍵是相同的,而在 multiset 中,可以存在相同的鍵值。

Multiset 鍵用於實現二叉搜尋樹。

什麼是 multiset::equal_range()?

multiset::equal_range() 函式是 C++ STL 中的一個內建函式,它在 <set> 標頭檔案中定義。equal_range() 獲取 multiset 容器中相等元素的範圍。

此函式返回一個範圍的邊界,該範圍包括容器中所有等於我們傳遞給函式的引數的元素。

語法

ms_name.equal_range(value_type& val);

引數

該函式接受一個引數:

  • val - 我們在容器中搜索其範圍的值。

返回值

此函式返回一對下界和上界,其值等於

示例

輸入

std::multiset<int> mymultiset = {1, 2, 2, 3, 4};
mymultiset.equal_range(2);

輸出

2 2

示例

 線上演示

#include <bits/stdc++.h>
using namespace std;
int main(){
   multiset<int> check;
   check.insert(10);
   check.insert(20);
   check.insert(30);
   check.insert(40);
   check.insert(50);
   check.insert(60);
   check.insert(70);
   check.insert(80);
   cout<<"Elements are: ";
   for (auto i = check.begin(); i!= check.end(); i++)
      cout << *i << " ";
   //lower bound and upper bound
   auto i = check.equal_range(30);
   cout<<"\nThe lower bound of 30 is " << *i.first;
   cout<<"\nThe upper bound of 30 is " << *i.second;
   // last element
   i = check.equal_range(20);
   cout<<"\nThe lower bound of 20 is " << *i.first;
   cout<<"\nThe upper bound of 20 is " << *i.second;
   i = check.equal_range(80);
   cout<<"\nThe lower bound of 80 is " << *i.first;
   cout<<"\nThe upper bound of 80 is " << *i.second;
   return 0;
}

輸出

Elements are: 10 20 30 40 50 60 70 80
The lower bound of 30 is 30
The upper bound of 30 is 40
The lower bound of 20 is 20
The upper bound of 20 is 30
The lower bound of 80 is 80
The upper bound of 80 is 8

更新於: 2020-04-17

134 次瀏覽

開啟你的職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.