在C ++ STL中设置upper_bound()函数
在本文中,我们将讨论C++STL中的set::upper_bound(),其语法,工作原理和返回值。
C++STL中的设置是什么?
C++STL中的集合是必须按常规顺序具有唯一元素的容器。集必须具有唯一元素,因为元素的值标识该元素。一旦在集合容器中添加了值,以后就无法修改,尽管我们仍然可以删除或将值添加到集合中。集用作二进制搜索树。
设置了什么::upper_bound()?
upper_bound()是C++STL中的内置函数,在<set>头文件中声明。upper_bound()将迭代器返回到我们希望找到其上限的值的上限。该函数返回迭代器,该迭代器指向我们希望找到其上限的值的下一个直接元素。
语法
name_of_set.upper_bound(consttype_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