rationale for std::lower_bound and std::upper_bound?

后端 未结 10 1525
傲寒
傲寒 2021-01-30 08:13

STL provides binary search functions std::lower_bound and std::upper_bound, but I tend not to use them because I\'ve been unable to remember what they do, because their contract

10条回答
  •  遥遥无期
    2021-01-30 08:42

    I accepted Brian's answer, but I just realized another helpful way of thinking about it which adds clarity for me, so I'm adding this for reference.

    Think of the returned iterator as pointing, not at the element *iter, but just before that element, i.e. between that element and the preceding element in the list if there is one. Thinking about it that way, the contracts of the two functions become symmetric: lower_bound finds the position of the transition from =val, and upper_bound finds the position of the transition from <=val to >val. Or to put it another way, lower_bound is the beginning of the range of items that compare equal to val (i.e. the range that std::equal_range returns), and upper_bound is the end of them.

    I wish they would talk about it like this (or any of the other good answers given) in the docs; that would make it much less mystifying!

提交回复
热议问题