Saturday, January 06, 2007

std::lower_bound has requirement on predicate

As this discussion points out:

In DEBUG build, the std::lower_bound implementation defines "_DEBUG_ORDER_SINGLE_PRED". This macro verifies that the collection is sorted. In order to do this, it obviously needs to compare A with A.

std::lower_bound(la.begin(), la.end(), 3, A::LessOp()) will, as you point out, compare the elements from la.begin to la.end to 3, using your own operator. As described by the documentation of lower_bound, the range will have to be sorted for lower_bound to work, and that's where the operator()(A,A) comes into play. When you compile your project in debug mode, a sanity check goes through the entire range comparing one element against the next (in this case A against A) using your custom predicate, confirming that they are truly sorted. When the sort check completes, lower_bound will start doing what you expect it to do: compare elements against your supplied int, using the supplied operator.

0 Comments:

Post a Comment

<< Home