std::set, how do lower_bound and upper_bound work?(std::set,lower_bound 和 upper_bound 是如何工作的?)
问题描述
我有这段简单的代码:
#include <iostream>
#include <set>
using std::set;
int main(int argc, char argv) {
set<int> myset;
set<int>::iterator it_l, it_u;
myset.insert(10);
it_l = myset.lower_bound(11);
it_u = myset.upper_bound(9);
std::cout << *it_l << " " << *it_u << std::endl;
}
这将打印 1 作为 11 的下限,并将 10 作为 9 的上限.
This prints 1 as lower bound for 11, and 10 as upper bound for 9.
我不明白为什么要打印 1.我希望使用这两种方法来获取给定上限/下限的一系列值.
I don't understand why 1 is printed. I was hoping to use these two methods to get a range of values for given upper bound / lower bound.
推荐答案
来自 <std::set::lower_bound:
返回值
迭代器指向第一个不小于键的元素.如果没有找到这样的元素,一个过去的迭代器(见 end()) 被返回.
Iterator pointing to the first element that is not less than key. If no such element is found, a past-the-end iterator (see end()) is returned.
在您的情况下,由于您的集合中没有不小于(即大于或等于)11 的元素,因此将返回一个过去的迭代器并将其分配给 it_l.然后在你的行中:
In your case, since you have no elements in your set which is not less (i.e. greater or equal) than 11, a past-the-end iterator is returned and assigned to it_l. Then in your line:
std::cout << *it_l << " " << *it_u << std::endl;
您正在推迟这个过去的迭代器 it_l:这是未定义的行为,并且可能导致任何结果(测试中的 1、0 或其他编译器的任何其他值,或者程序甚至可能崩溃).
You're deferencing this past-the-end iterator it_l: that's undefined behavior, and can result in anything (1 in your test, 0 or any other value with an other compiler, or the program may even crash).
您的下限应该小于或等于上限,并且您不应该在循环或任何其他测试环境之外取消引用迭代器:
Your lower bound should be less than, or equal to to the upper bound, and you should not dereference the iterators outside a loop or any other tested environment:
#include <iostream>
#include <set>
using std::set;
int main(int argc, char argv) {
set<int> myset;
set<int>::iterator it_l, it_u;
myset.insert(9);
myset.insert(10);
myset.insert(11);
it_l = myset.lower_bound(10);
it_u = myset.upper_bound(10);
while(it_l != it_u)
{
std::cout << *it_l << std::endl; // will only print 10
it_l++;
}
}
这篇关于std::set,lower_bound 和 upper_bound 是如何工作的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:std::set,lower_bound 和 upper_bound 是如何工作的?
基础教程推荐
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- CString 到 char* 2021-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 初始化列表*参数*评估顺序 2021-01-01
