Search code examples
c++stdset

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


Say I have a set

s={1 5 10}

Now if I run a loop for [0,2] and everytime check for the strictly lower than upper bound of the set than how can I handle lower value than s.begin() ?See the code for further clarification-

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

Here For strictly lower than upper_bound of 0 -> 3.Here one possible solution may be always checks for greater or equal value than s.begin().Is there any other better way to do that?


Solution

  • You can return a std::optional if (it == s.begin()) and accordingly print some suitable default such as 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