简体   繁体   中英

Binary Search C++ STL

I have a vector of unordered_map which is sorted based on the comparer function I defined. I would like to use binary search to look for one of the value using the comparer function as well. However, binary search only return bool and I need the index / iterator of the result. What could I do?

#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
}
#include <algorithm>
using namespace std;

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM