5

私は完璧に動作する次のコードを持っています。

目的: 数 n が与えられたとき、n の前後の数を見つけます。

以下の例に基づいて: n = 50 の場合、i は 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 より小さいものを指す何か他のもの。

前もって感謝します!:)

4

3 に答える 3

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

もちろん、セット内に 50 未満の要素があることが確実でない限り、その反復子を逆参照しないでください。そのためかどうかを確認できますit == myset.begin()

于 2012-05-12T20:47:01.987 に答える
1

あなたがしたいlower_bound(49)。またはlower_bound(50)、必要に応じて元に戻す準備をしておくこともできます。

于 2012-05-12T20:49:06.343 に答える
1

lower_boundChris が 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;
}
于 2012-05-12T20:46:54.977 に答える