Подтвердить что ты не робот

Бинарный поиск С++ STL

У меня есть вектор unordered_map, который сортируется на основе функции сравнения, которую я определил. Я хотел бы использовать бинарный поиск для поиска одного из значений с помощью функции сравнения. Однако бинарный поиск возвращает только bool, и мне нужен индекс/итератор результата. Что я могу сделать?

4b9b3361

Ответ 1

#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
}

Ответ 2

#include <algorithm>
using namespace std;

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