c++ - Inquiry on std::binary_search() -
i'm looking @ using std::binary_search() (from library) determine whether or not instance of exists in list. want know how works before begin using it.
my understanding uses comparison (and user-defined structs/classes need access user-defined compare function) find out if instance of object exists within list/vector. according website (http://www.cplusplus.com/reference/algorithm/binary_search/), range used is:
[first, last)
so not including last because have compare last against last + 1?
also user-defined compare function's logic not matter long differentiates between properties within object/class. correct?
for example, if struct/class consisted of following:
coord { int x; int y; }
i have make sure compare function differentiates (in manner, such greater-than/less-than comparison) x , y properties of elements , b in list/vector.
std::binary_search() implemented common binary search algorithm, performs @ log2(n)+1 element comparisons. (for more information on how binary search implemented check link)
so not including last because have compare last against last + 1?
no, reason facilitate use. can call function as:
std::binary_search (v.begin(), v.end(), 42)
notice v.end() returns iterator element past end of sequence. hence, not point element, , shall not evaluated in search.
also user-defined compare function's logic not matter long differentiates between properties within object/class. correct?
the compare function used binary_search() in order know if element looking before element being tested of after it. in other words, compare function must able compare 2 elements , return if first 1 "lower" second 1 (must placed in container before second one).
for coord example write comparator function like:
struct lessthankey { inline bool operator() (const coord& lhs, const coord& rhs) { return (lhs.x < rhs.x) || ((lhs.x == rhs.x) && (lhs.y < rhs.y)); } }; std::binary_search(v.begin(), v.end(), coord{42, 42}, lessthankey());
Comments
Post a Comment