问题描述
我有这段简单的代码:
#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 是如何工作的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!