【问题标题】:std::set, how do lower_bound and upper_bound work?std::set,lower_bound 和 upper_bound 是如何工作的?
【发布时间】:2016-11-08 10:15:45
【问题描述】:

我有这段简单的代码:

#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。我希望使用这两种方法来获取给定上限/下限的一系列值。

【问题讨论】:

  • 在尝试取消引用迭代器之前检查myset.end()

标签: c++ set containers


【解决方案1】:

来自std::set::lower_bound上的cppreference.com

返回值

迭代器指向第一个不小于键的元素。如果没有找到这样的元素,则返回一个过去的迭代器(请参阅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++;
    }
}

【讨论】:

  • 那么在这种情况下lower_bound(9) == upper_bound(9)?
  • 在这种情况下,是的。
  • 这些名称具有误导性。
  • lower_bound(10) 和upper_bound(10) 会有不同的值,因为upper_bound 返回第一个大于key 的值的迭代器,而lower_bound 返回第一个大于key 的值的迭代器或等于
  • @user8469759 我在回答中添加了一个更完整的示例
【解决方案2】:

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

【讨论】:

  • 如何获得给定下限的一系列值?在我看来,它应该将相同的迭代器返回到 10。显然它不能以这种方式工作。
【解决方案3】:

lower_bound() 将迭代器返回到第一个不少于 的元素。如果没有找到这样的元素,则返回 end()。

请注意,使用 end() 返回的迭代器指向集合中结束后的元素。这是标准容器的正常行为,表明出现问题。根据经验,您应该始终检查这一点并采取相应措施。

您的代码是上述情况的示例,因为集合中没有不少于 11 的元素。打印的 '1' 只是来自 end() 迭代器的垃圾值。

用下面的sn-p自己看吧:

#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);
   if (it_l == myset.end()) {
       std::cout << "we are at the end" << std::endl;
   }

   it_u = myset.upper_bound(9);

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

【讨论】:

    猜你喜欢
    • 2020-05-11
    • 2014-06-26
    • 1970-01-01
    • 2015-10-27
    • 1970-01-01
    • 1970-01-01
    • 2011-11-21
    • 2017-08-30
    • 1970-01-01
    相关资源
    最近更新 更多