Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mystical restriction on std::binary_search

People also ask

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.

Does STD find use binary search?

The algorithm to use is std::binary_search , that directly returns a bool representing whether the searched value has equivalent elements in the collection.

How do you use binary search in CPP?

Binary Search in C++ This method is done by starting with the whole array. Then it is halved. If the required data value is greater than the element at the middle of the array, then the upper half of the array is considered. Otherwise, the lower half is considered.


If your goal is to find if there is a Human with a given name, then the following should work for sure:

const std::string& get_name(const Human& h)
{
    return h.name;
}

...

bool result = std::binary_search(
    boost::make_transform_iterator(v.begin(), &get_name),
    boost::make_transform_iterator(v.end(), &get_name),
    name_to_check_against);

[Complete rewrite; disregard the comments]

The wording has been changed from C++03 to C++0x. In the latter, there is no more requirement for T to be less-than comparable, presumably to alleviate this unnecessary restriction.

The new standard only requires that comp(e, value) implies !comp(value, e). So as long as your comparator implements both directions, you should be able to legally search a string as the value with a comparator functor that implements both asymmetric comparisons (i.e. your "Attempt 3").