Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Binary Search C++ STL

Tags:

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?

like image 442
Steveng Avatar asked Nov 26 '10 09:11

Steveng


People also ask

Is there STL for binary search?

Binary search is a widely used searching algorithm that requires the array to be sorted before search is applied.

What does Binary_search return in C++?

1. binary_search: binary_search(start_ptr, end_ptr, num): This function returns true if the element is present in the container, else returns false.

Does C++ have built in binary search?

C++ bsearch()The bsearch() function in C++ performs a binary search of an element in an array of elements and returns a pointer to the element if found. The bsearch() function requires all elements less than the element to be searched to the left of it in the array.

What is binary search in C programming?

A Binary Search is a sorting algorithm, that is used to search an element in a sorted array. A binary search technique works only on a sorted array, so an array must be sorted to apply binary search on the array.


2 Answers

#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
}
like image 191
T33C Avatar answered Oct 01 '22 14:10

T33C


#include <algorithm>
using namespace std;

it = lower_bound(a.begin, a.end(), value, cmp);
like image 21
Teodor Pripoae Avatar answered Oct 01 '22 14:10

Teodor Pripoae