문제

I have the following for a set

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

How do i do this for a map? i think the program below seem to be using the first value of the map instead of the second value hence i am getting errors.

How do i set it to use the second value?

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

Actual Code that gives me wrong values when using with map, works when i use 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;
}
도움이 되었습니까?

해결책

If you want to search a map for a particular value (not key) then you have to iterate sequentially over the map and check each value, as find(), lower_bound(), upper_bound() all use the key.

In the posted code, you could exchange the value and the key, which would allow you to search the map as the previous set was searched:

myset[10] = 0;
myset[20] = 2;
myset[30] = 3;
myset[40] = 4;
myset[50] = 5;
myset[60] = 6;
myset[70] = 7;
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top