지도

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

는' 요소인지를 매핑, '확실하지 않은 방법이 컴파일을 ,'std :: map'은 키와 값의 쌍을 가지고 있습니다. 실제 코드 샘플을 게시하십시오. 붙여 넣은 stuff.Post 귀하의 문제를 컴파일하고 보여줍니다 minimalist 코드 샘플을 게시하십시오. –

+0

요청시, – mister

+0

편집이 작업은 분명히 원하는대로 작동하지 않습니다. [upper_bound] (http://www.sgi.com/tech/stl/Map.html)의 정의를 참조하십시오. 그것은 말합니다 :'k보다 큰 키를 가진 첫 번째 요소를 찾습니다 .'. 또한'upper_bound'는 정렬 된 구조와 관련이 있습니다. 소트가 보증되어 있지 않은 맵의 값에는 무관계합니다. – Vikas

답변

2

특정 값 (키가 아닌)에 대한 map을 검색하려면 다음 순차적으로 맵을 반복하고 각 값을 확인해야합니다. find(), lower_bound(), upper_bound() 모두 키를 사용해야합니다. 게시 된 코드에서

, 당신은 교환 할 수있는 value 및 검색된 이전 setmap를 검색 할 수 있도록 할 것 key :

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