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