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 的上限。

我不明白为什么要打印 1。我希望使用这两种方法来获取给定上限/下限的一系列值。

原文由 user8469759 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 742
2 个回答

cppreference.comstd::set::lower_bound

返回值

指向不 小于 key的第一个元素的迭代器。如果没有找到这样的元素,则返回一个过去的迭代器(参见 end() )。

在您的情况下,由于您的集合中没有不小于(即大于或等于)11 的元素,因此返回一个结束迭代器并将其分配给 it_l 。然后在你的行中:

 std::cout << *it_l << " " << *it_u << std::endl;

您正在推迟这个过去的迭代器 it_l :这是未定义的行为,并且可能导致任何结果(测试中的 1、0 或其他编译器的任何其他值,或者程序甚至可能崩溃)。

您的下限应该小于或等于上限,并且您不应该在循环或任何其他测试环境之外取消引用迭代器:

 #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++;
    }
}

原文由 rgmt 发布,翻译遵循 CC BY-SA 4.0 许可协议

这是UB。你的 it_l = myset.lower_bound(11); 返回 myset.end() (因为它在集合中找不到任何东西),你没有检查,然后你基本上打印出过去迭代器的值.

原文由 SingerOfTheFall 发布,翻译遵循 CC BY-SA 3.0 许可协议

推荐问题