C++ STL 中的 set::upper_bound() 函式
在本文中,我們將討論 C++ STL 中的 set::upper_bound(),包括其語法、工作原理和返回值。
什麼是 C++ STL 中的 Set?
C++ STL 中的 Set 是一種容器,其元素必須是唯一的,並且按照一定的順序排列。Set 中的元素必須唯一,因為元素的值決定了元素的標識。一旦將一個值新增到 Set 容器中,以後就不能修改該值,儘管我們仍然可以刪除或新增值到 Set 中。Set 被用作二叉搜尋樹。
什麼是 set::upper_bound()?
upper_bound() 是 C++ STL 中的一個內建函式,它在 <set> 標頭檔案中宣告。upper_bound() 返回一個迭代器,指向我們想要查詢其上界的元素的上界。該函式返回一個迭代器,指向我們想要查詢其上界的元素的緊鄰下一個元素。
語法
name_of_set.upper_bound(const type_t& value);
引數
此函式接受一個引數,即要查詢其上界的元素的值。
返回值
此函式返回一個迭代器,指向大於該值的緊鄰下一個元素。
示例
Input: set<int> myset = {1, 2, 3, 4, 5};
Myset.upper_bound(3);
Output: Upper bound = 4示例
#include <bits/stdc++.h>
using namespace std;
int main(){
set<int> Set;
Set.insert(9);
Set.insert(7);
Set.insert(5);
Set.insert(3);
Set.insert(1);
cout<<"Elements are : ";
for (auto i = Set.begin(); i!= Set.end(); i++)
cout << *i << " ";
auto i = Set.upper_bound(5);
cout <<"\nupper bound of 5 in the set is: ";
cout << (*i) << endl;
i = Set.upper_bound(1);
cout<<"upper bound of 1 in the set is: ";
cout << (*i) << endl;
return 0;
}輸出
如果我們執行上述程式碼,它將生成以下輸出:
upper bound of 5 in the set is: 7 upper bound of 1 in the set is: 3
示例
#include <iostream>
#include <set>
int main (){
std::set<int> Set;
std::set<int>::iterator one, end;
for (int i=1; i<10; i++)
Set.insert(i*10);
one = Set.lower_bound (20);
end = Set.upper_bound (40);
Set.erase(one , end); // 10 20 70 80 90
std::cout<<"Elements are: ";
for (std::set<int>::iterator i = Set.begin(); i!=Set.end(); ++i)
std::cout << ' ' << *i;
std::cout << '\n';
return 0;
}輸出
如果我們執行上述程式碼,它將生成以下輸出:
Elements are : 10 50 60 70 80 90
廣告
資料結構
網路
關係資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP