2012-05-12 4 views
4

나는 완벽하게 작동합니다 다음과 같은 코드가 있습니다.STL 컨테이너를 사용하여 컨테이너 upper_bound

목표 : 숫자 n이 주어지면 n의 다음 및 이전 번호를 찾습니다.

아래 예를 기반으로합니다. n = 50이면 60과 40을 따로 따로 섭니다.

upper_bound를 사용하여 60을 얻을 수 있습니다. 하지만 50을하기 전에 숫자를 얻는 방법을 제공 알고리즘을 찾을 것 같습니다. http://www.cplusplus.com/reference/stl/set/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 

, 그것은 UPPER_BOUND 말한다 "비교하지 않는 컨테이너의 첫 번째 요소를 가리키는 반복자를 반환 미만 X을"하지만, 뭔가 다른 무언가를 가리키는이 있는지 메신저가 x보다 작게 비교하십시오.

미리 감사드립니다. :)

+3

'lower_bound'는 어떻습니까? – chris

답변

6
it = myset.lower_bound(50); 
--it; 

생각이 가 요소보다 50 년가 확실하지 않으면 그 반복자를 역 참조하지 않습니다 세트. 그게 it == myset.begin()인지 확인할 수 있습니다.

+0

집합에 50이 없으면 어떻게됩니까? –

+0

지금은 너무 어리 석다. 내가해야 할 일은 "--itup;"을 사용하는 것뿐입니다. 낮은 범위에 도달하려면 2 번. 감사! – mister

+0

@AlanStokes 필요에 따라 여전히 위 또는 아래 범위로 이동합니다. 각각 60 및 40입니다 – mister

1

chris와 같이 lower_bound을 사용하면 sgi : http://www.sgi.com/tech/stl/lower_bound.html 및 MSDN : http://msdn.microsoft.com/en-us/library/awxks70z%28v=vs.80%29.aspx을 참조하십시오.

lower_bound은 순서가 원하는대로 유지되도록 삽입이 발생할 위치를 반환합니다.

그래서

itlow = myset.lower_bound (50); // check if this is not pointing to myset.end() 
--itlow; // should still check if this is in your container really 
cout << "upper_bound at position " << (*itup) << "lower bound" << (*itlow) << endl; 

더 나은 버전 나는

// check whether lower_bound returns myset.end() or myset.begin() for sensible and safe assignment 
if (myset.lower_bound(50) != myset.end() && myset.lower_bound(50) != myset.begin()) 
{ 
    itlow = myset.lower_bound(50); 
    --itlow; 
} 
물론
1

당신은 lower_bound(49)을 원합니다. 또는 lower_bound(50)을하고 필요할 경우 다시 준비 할 수 있습니다.

+1

lower_bound (49)에서 50을 반환하지 않습니까? – mister

+0

가, 예. 첫 번째 값> = 매개 변수를 반환합니다. 그래서 예, lower_bound (50), 이전 요소가있는 경우 *가 답입니다. 이 두 사람은 항상 나를 혼란스럽게 만듭니다 .-( –

관련 문제