如何在 std::set 中获得严格低于上限的值?

How can I get the strictly lower value than upper bound in a std::set?

说我有一套

s={1 5 10}

现在,如果我 运行 一个 [0,2] 的循环,并且每次都检查严格低于集合上限的值,那么我如何处理低于 s.begin() 的值?请参阅进一步说明的代码-

    set<int>s;
    s={1,5,10};
    for(auto i:s)
    {
        cout<<i<<"\n\n";
        for(int j=0;j<3;++j)
        {
            auto it=s.upper_bound(j);
            cout<<"For upper_bound of "<<j<<" ->"<<*it<<"~~~";
            it--;
            cout<<"For strictly lower than upper_bound of "<<j<<" ->"<<*it<<"\n";
        }
        cout<<endl;
    }

这里 For strictly lower than upper_bound of 0 -> 3。这里一种可能的解决方案可能总是检查大于或等于 s.begin() 的值。还有其他更好的方法吗?

您可以 return a std::optional if (it == s.begin()) 并相应地打印一些合适的默认值,例如 none.

auto strictly_lower = [&] () -> std::optional<int> {
                if(it == s.begin()) {
                    return std::nullopt;
                }
                it--;
                return std::optional{*it};
            }();
            
std::cout<<"For strictly lower than upper_bound of "<<j<<" ->"<< (strictly_lower.has_value() ? std::to_string(*strictly_lower) : "none") <<"\n";

Code Link