2012-05-13 60 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 

我如何對地圖做以下?我認爲下面的程序似乎是使用地圖的第一個值而不是第二個值,因此我得到錯誤。

如何將其設置爲使用第二個值?

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'包含一個鍵值對。請發佈實際的代碼示例。不要複製粘貼的東西。發佈最低限度的代碼示例,編譯並演示您的問題。 –

+0

根據要求,編輯 – mister

+0

這顯然不會按你所希望的那樣工作。請參閱[upper_bound](http://www.sgi.com/tech/stl/Map.html)的定義。它說:「找出第一個元素的關鍵大於k.'。 'upper_bound'也與排序結構有關。這對於不保證排序的地圖的值是無關緊要的。 – Vikas

回答

2

如果你要搜索一個map特定值(不是鍵),那麼你必須在地圖上依次迭代並檢查每個值,因爲find()lower_bound()upper_bound()全部使用密鑰。

在發佈代碼,你可以交換valuekey,這樣可以讓你搜索map與以前set被搜查:

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