使用STL Container设置upper_bound

时间:2012-05-12 20:40:16

标签: c++ stl set

我有以下完美的代码。

目标:给定数字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 好”但是我确定还有其他的东西指向比较小于的内容。

提前致谢! :)

3 个答案:

答案 0 :(得分:6)

it = myset.lower_bound(50);
--it;

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

答案 1 :(得分:1)

像Chris一样使用lower_bound,请参阅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 :(得分:1)

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