我有一组
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
使用地图时给出错误值的实际代码,当我使用set时工作:
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;
}
答案 0 :(得分:2)
如果您要在map
中搜索特定值(而不是键),则必须在地图上按顺序迭代并检查每个值,如find()
,lower_bound()
,{ {1}}都使用密钥。
在发布的代码中,您可以与upper_bound()
和value
进行交换,这样您就可以搜索key
,因为之前搜索了map
:
set