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