2012-05-13 4 views
-3

のためのSTLコンテナUPPER_BOUND&LOWER_BOUNDを使用して、私はマップ

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 

がどのように私はマップのためにこれを行うのですセットのために、次がありますか?私は以下のプログラムは、2番目の値の代わりにマップの最初の値を使用しているようだので、私はエラーが発生していると思う。

第2の値を使用するように設定するにはどうすればよいですか?

map<int,int> myset; 
map<int,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).second << endl; 
//output: some random value returns 
マップを使用しているとき私に間違った値を示します

実際のコードは、私が設定し使用するときに動作します :

int x = 50; 

map<int,int> myset; 
//for (int i=1; i<10; i++) myset.insert(i*10); // 10 20 30 40 50 60 70 80 90 
myset[0] = 10; 
myset[2] = 20; 
myset[3] = 30; 
myset[4] = 40; 
myset[5] = 50; 
myset[6] = 60; 
myset[7] = 70; 


map<int,int>::iterator begin,upbound,lobound,it; 
    map<int,int>::reverse_iterator end; 
end = myset.rbegin(); 
begin = myset.begin(); 
upbound=myset.upper_bound(x); 
lobound=myset.lower_bound(x); 
lobound--; 

if(myset.size()==1) 
{ 
    cout << "upper_range = " << x <<endl; 
    cout << "lower_range = " << x <<endl; 

} 
else if(x == (*begin).second) 
{ 
    cout << "upper_range = " << (*upbound).second <<endl; 
    cout << "lower_range = " << end->second <<endl; 

} 
else if(x == end->second) 
{ 
    cout << "upper_range = " << (*begin).second <<endl; 
    cout << "lower_range = " << (*lobound).second <<endl; 

} 
else 
{ 
    cout << "start = " << (*begin).second <<endl; 
    cout << "end = " << end->second<<endl; 
    cout << "upper_range = " << (*upbound).second <<endl; 
    cout << "lower_range = " << (*lobound).second <<endl; 
} 
+3

' MYSETをマップ;'これはコンパイルする方法がわかりませんの'std :: map'はキーと値のペアを保持します。実際のコードsample.notを貼り付けて貼り付けてください。あなたの問題をコンパイルして示す最小限のコードサンプルを貼り付けてください。 –

+0

要請、編集 – mister

+0

これは明らかにあなたが望むように動作しません。 [upper_bound](http://www.sgi.com/tech/stl/Map.html)の定義を参照してください。それは言う: 'kより大きいキーを持つ最初の要素を見つけます。また、 'upper_bound'はソートされた構造体に関連します。ソートされていないマップの値とは無関係です。 – Vikas

答えて

2

あなたが特定の値(キーではない)のためmapを検索したい場合は、あなた地図上を順番に反復して各値を確認する必要があります。find()lower_bound()upper_bound()はすべてキーを使用します。投稿のコードで

、あなたは前setが検索されたとして、あなたがmapを検索することが可能になるvaluekey、交換することができます:

myset[10] = 0; 
myset[20] = 2; 
myset[30] = 3; 
myset[40] = 4; 
myset[50] = 5; 
myset[60] = 6; 
myset[70] = 7; 
+0

他の方法でスイッチングしていないのですか? – mister

+0

'map :: find()'、 'map :: lower_bound()'などを使用しない場合 – hmjd