【问题标题】:using STL Container set upper_bound使用 STL 容器设置 upper_bound
【发布时间】:2012-05-20 23:43:33
【问题描述】:

我有以下完美的代码。

目的:给定一个数n,找出n的下一个和前一个数。

基于以下示例:如果 n = 50,那么我将分别得到 60 和 40。

我可以通过使用upper_bound 获得60。但是我如何获得 50 之前的数字我似乎找不到提供的算法来做到这一点。

set<int> myset;
set<int>::iterator it,itlow,itup;

for (int i=1; i<10; i++) myset.insert(i*10); // 10 20 30 40 50 60 70 80 90
itup=myset.upper_bound (50);                 // 
cout << "upper_bound at position " << (*itup) << endl;
    //output: 60

关于http://www.cplusplus.com/reference/stl/set/lower_bound/,它说upper_bound“返回一个迭代器,指向容器中不小于x的第一个元素”但我确定还有其他东西指向比较小于 x

提前致谢! :)

【问题讨论】:

    标签: c++ stl set


    【解决方案1】:

    使用 lower_bound 就像 chris 所说的,请参阅 sgi:http://www.sgi.com/tech/stl/lower_bound.html 和 MSDN:http://msdn.microsoft.com/en-us/library/awxks70z%28v=vs.80%29.aspx

    lower_bound 将返回发生插入的位置,以便保持您想要的顺序。

    所以

    itlow = myset.lower_bound (50); // check if this is not pointing to myset.end()
    --itlow; // should still check if this is in your container really
    cout << "upper_bound at position " << (*itup) << "lower bound" << (*itlow) << endl;
    

    我认为更好的版本

    // check whether lower_bound returns myset.end() or myset.begin() for sensible and safe assignment
    if (myset.lower_bound(50) != myset.end() && myset.lower_bound(50) != myset.begin())
    {
      itlow = myset.lower_bound(50);
      --itlow;
    }
    

    【讨论】:

      【解决方案2】:

      你想要lower_bound(49)。或者可能会做lower_bound(50) 并准备好在需要时返回一个。

      【讨论】:

      • 在 lower_bound(49) 上它不会仍然返回 50 吗?
      • 呸,是的。它返回第一个值 >= 参数。所以是的,lower_bound(50) 和返回一个 如果有前一个元素 就是答案。这两个总是让我感到困惑:-(
      【解决方案3】:
      it = myset.lower_bound(50);
      --it;
      

      当然,除非您确定 集合中有小于 50 的元素,否则不要取消引用该迭代器。你可以检查 it == myset.begin() 是否。

      【讨论】:

      • 如果集合中没有 50 怎么办?
      • 现在我觉得自己好蠢。我所要做的就是使用“--itup;” 2次到达较低的范围。谢谢!
      • @AlanStokes 它仍会根据需要进入上限或下限。分别是 60 和 40
      猜你喜欢
      • 1970-01-01
      • 2020-08-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-08
      • 2012-03-16
      • 2012-11-12
      • 1970-01-01
      相关资源
      最近更新 更多