【问题标题】:How can I get the strictly lower value than upper bound in a std::set?如何在 std::set 中获得严格低于上限的值?
【发布时间】:2020-12-04 05:41:51
【问题描述】:

说我有一套

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 -&gt; 3。这里一种可能的解决方案是始终检查大于或等于s.begin() 的值。还有其他更好的方法吗?

【问题讨论】:

    标签: c++ stdset


    【解决方案1】:

    如果(it == s.begin()),您可以返回一个 std::optional 并相应地打印一些合适的默认值,例如无。

    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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-10-13
      • 1970-01-01
      • 1970-01-01
      • 2014-05-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多