
在 C++ 语言中的 标准模板库 ( STL , Standard Template Library ) 中的 std::set 集合容器 类提供了一个 lower_bound 成员函数 ;
该 lower_bound 函数返回一个迭代器对象 , 该 迭代器对象 指向在 set 有序集合中 第一个 大于等于 给定键值的元素 , 继续将迭代器 自增 , 即可访问 set 集合容器中 大于等于指定元素的后续元素 ;
如果集合中不存在这样的元素 , 即 集合中的最小值 都 大于 给定的值 , 则返回的 迭代器 将等于 end() 末尾迭代器 ;
std::set#lower_bound 函数原型如下 :
iterator lower_bound(const key_type& k) const;在下面的代码中 , 创建 set 集合容器 , 其中包含 { 1, 2, 4, 5 } 四个值 ;
// 初始化
set<int> mySet = { 1, 2, 4, 5 };调用 lower_bound 函数 , 获取 set 集合容器中 , 大于等于 3 的最小元素 ;
mySet.lower_bound(3);代码示例 :
#include "iostream"
using namespace std;
#include "set"
int main() {
// 初始化
set<int> mySet = { 1, 2, 4, 5 };
// 获取大于等于 3 的元素
auto it = mySet.lower_bound(3);
if (it != mySet.end()) {
cout << "找到了大于等于 3 的最小元素是 : " << *it << endl;
}
else {
cout << "没有大于等于 3 的元素 " << endl;
}
// 控制台暂停 , 按任意键继续向后执行
system("pause");
return 0;
};执行结果 :
找到了大于等于 3 的最小元素是 : 4 请按任意键继续. . .

在 C++ 语言中的 标准模板库 ( STL , Standard Template Library ) 中的 std::set 集合容器 类提供了一个 upper_bound 成员函数 ;
该 upper_bound 函数返回一个迭代器对象 , 该 迭代器对象 指向在 set 有序集合中 第一个 大于 给定键值的元素 , 继续将迭代器 自增 , 即可访问 set 集合容器中 大于指定元素的后续元素 ;
如果集合中不存在这样的元素 , 即 集合中的最小值 都 小于 给定的值 , 则返回的 迭代器 将等于 end() 末尾迭代器 ;
std::set#upper_bound 函数原型如下 :
iterator upper_bound(const key_type& k) const;代码示例 :
#include "iostream"
using namespace std;
#include "set"
int main() {
// 初始化
set<int> mySet = { 1, 2, 3, 4, 5 };
// 获取大于 3 的元素
auto it = mySet.upper_bound(3);
if (it != mySet.end()) {
cout << "找到了大于 3 的最小元素是 : " << *it << endl;
}
else {
cout << "没有大于 3 的元素 " << endl;
}
// 控制台暂停 , 按任意键继续向后执行
system("pause");
return 0;
};执行结果 :
找到了大于 3 的最小元素是 : 4 请按任意键继续. . .

在 C++ 语言中的 标准模板库 ( STL , Standard Template Library ) 中的 std::set 集合容器 类提供了一个 equal_range 成员函数 ;
equal_range 函数返回一对迭代器 , 分别表示集合中与给定键值相等的元素范围 ; 这两个迭代器放在 对组 中 , 类型为 std::pair<iterator, iterator> ;
返回的 两个迭代器 范围 是 前闭后开 区间 ;
由于 std::set 中的元素是唯一的 ,
equal_range 函数原型如下 :
std::pair<iterator, iterator> equal_range(const key_type& k) const;代码示例 :
#include "iostream"
using namespace std;
#include "set"
int main() {
// 初始化
set<int> mySet = { 1, 2, 3, 4, 5 };
// 获取等于 3 的元素范围
auto pair_3 = mySet.equal_range(3);
if (pair_3.first != mySet.end()) {
cout << "找到了等 3 的元素"<< endl;
}
else {
cout << "没有找到了等 3 的元素" << endl;
}
// 控制台暂停 , 按任意键继续向后执行
system("pause");
return 0;
};执行结果 :
找到了等 3 的元素 请按任意键继续. . .
