C++ STL 中的 set::equal_range() 函式
本文將討論 C++ STL 中的 set::equal_range() 函式,包括其語法、工作原理和返回值。
什麼是 C++ STL 中的 Set?
C++ STL 中的 Set 是容器,其元素必須唯一且按一定順序排列。Set 中的元素必須唯一,因為元素的值標識了該元素。一旦將值新增到 Set 容器中,就不能再修改該值,儘管我們仍然可以刪除或新增 Set 中的值。Set 使用二叉搜尋樹。
什麼是 set::equal_range()?
equal_range() 函式是 C++ STL 中的內建函式,在標頭檔案中定義。此函式返回 Set 容器中包含作為函式引數傳遞的值的範圍。Set 包含所有唯一值,因此在找到的範圍內等效的值將是單個值。如果容器中不存在該值,則範圍將為零,兩個迭代器都指向第一個位置。
語法
Set1.equal_range(const type_t& value);
引數
此函式接受一個引數,即要查詢的元素。
返回值
此函式返回一個pair,或者可以說是一個迭代器範圍,從容器的下界開始到容器中要查詢的元素結束。
示例
Input: set<int> myset = {10, 20, 30, 40};
Output: lower bound of 30 is 30示例
#include <bits/stdc++.h>
using namespace std;
int main(){
set<int> mySet;
mySet.insert(10);
mySet.insert(20);
mySet.insert(30);
mySet.insert(40);
mySet.insert(50);
cout<<"Elements before applying range() Function : ";
for (auto i = mySet.begin(); i != mySet.end(); i++)
cout << *i << " ";
auto i = mySet.equal_range(30);
cout<<"\nlower bound of 30 is "<< *i.first;
cout<<"\nupper bound of 30 is "<< *i.second;
i = mySet.equal_range(40);
cout<<"\nlower bound of 40 is " << *i.first;
cout<<"\nupper bound of 40 is " << *i.second;
i = mySet.equal_range(10);
cout<<"\nlower bound of 10 is " << *i.first;
cout<<"\nupper bound of 10 is " << *i.second;
return 0;
}輸出
如果執行以上程式碼,則會生成以下輸出:
Elements before applying range() Function : 10 20 30 40 50 lower bound of 30 is 30 upper bound of 30 is 40 lower bound of 40 is 40 upper bound of 40 is 50 lower bound of 10 is 10 upper bound of 10 is 20
廣告
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP