std :: set,lower_bound和upper_bound如何工作?

use*_*759 9 c++ containers set

我有这么简单的代码:

#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;
}
Run Code Online (Sandbox Code Playgroud)

这将打印1作为11的下限,10作为9的上限.

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

was*_*ful 6

cppreference.comon std :: set :: lower_bound:

返回值

迭代器指向第一个不小于键的元素.如果找不到这样的元素,则返回一个past-the-end迭代器(参见end()).

在您的情况下,由于您的集合中没有不小于(即大于或等于)11的元素,因此返回并分配了过去的迭代器it_l.然后在你的行:

std::cout << *it_l << " " << *it_u << std::endl;
Run Code Online (Sandbox Code Playgroud)

您正在引用这个过去的迭代器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++;
    }
}
Run Code Online (Sandbox Code Playgroud)