Mystical restriction on std::binary_search

こ雲淡風輕ζ 提交于 2019-12-03 05:23:35

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").

Billy ONeal

I think what the standard is saying here is that the expression fucntor(a, b) needs to be a valid strict weak ordering, no matter if the algorithm decides to do something like functor(*begin, *(begin + 1)). Therefore, I think your comparator would need to supply an overload of operator()(Human, Human) in order to be conforming.

That said, I think this is one of those things not explicitly allowed by the standard, but for which few or no implementations exist which take advantage of the latitude offered by the standard.

I don't see it requiring anywhere in the standard that the types of the values passed to the comparison function (or to the < operator) by binary_search must be the same. So, formally I think it is perfectly fine to use a comparator that works with two differently types values.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!