问题描述
我有一段简单的代码:
#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 :
迭代器指向不小于键的第一个元素。如果找不到这样的元素,则使用过去的迭代器(请参见)返回。
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如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!