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

  • 本文关键字:std set c++ stdset
  • 更新时间 :
  • 英文 :


假设我有一套

s={1 5 10}

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

set<int>s;
s={1,5,10};
for(auto i:s)
{
cout<<i<<"nn";
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()的值。有其他更好的方法吗?

如果(it == s.begin()),您可以返回std::optional,并相应地打印一些合适的默认值,如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";

代码链接

最新更新