2010-11-26 174 views
18

我有一個unordered_map矢量,它是根據我定義的比較函數排序的。我想使用二進制搜索來使用比較器函數來查找其中的一個值。然而,二分查找只返回布爾,我需要結果的索引/迭代器。我能做什麼?二進制搜索C++ STL

回答

22
#include <algorithm> 
using namespace std; 

//!!!!! a must be sorted using cmp. Question indicates that it is.   
it = lower_bound(a.begin, a.end(), value, cmp); 

//Check that we have actually found the value. 
//If the requested value is missing 
//then we will have the value before where the requested value 
//would be inserted. 
if(it == a.end() || !cmp(*it, value)) 
{ 
    //element not found 
} 
else 
{ 
    //element found 
} 
15
#include <algorithm> 
using namespace std; 

it = lower_bound(a.begin, a.end(), value, cmp); 
+3

1或可能UPPER_BOUND或equal_range – 2010-11-26 09:39:00

+2

-1 LOWER_BOUND不一定返回的元素。如果元素丟失,它會返回元素,如果它在矢量中。 – T33C 2010-11-26 09:50:42