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

后端 未结 10 1732
傲寒
傲寒 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:58

    std::lower_bound
    

    Returns an iterator pointing to the first element in the range [first, last) that is not less than (i.e. greater or equal to) value.

    std::upper_bound
    

    Returns an iterator pointing to the first element in the range [first, last) that is greater than value.

    So by mixing both lower and upper bound you are able to exactly describe where your range begins and where it ends.

    Does this make any sense??

    Yes.

    Example:

    imagine vector

    std::vector data = { 1, 1, 2, 3, 3, 3, 3, 4, 4, 4, 5, 5, 6 };
    
    auto lower = std::lower_bound(data.begin(), data.end(), 4);
    
    1, 1, 2, 3, 3, 3, 3, 4, 4, 4, 5, 5, 6
                      // ^ lower
    
    auto upper = std::upper_bound(data.begin(), data.end(), 4);
    
    1, 1, 2, 3, 3, 3, 3, 4, 4, 4, 5, 5, 6
                               // ^ upper
    
    std::copy(lower, upper, std::ostream_iterator(std::cout, " "));
    

    prints: 4 4 4


    http://en.cppreference.com/w/cpp/algorithm/lower_bound

    http://en.cppreference.com/w/cpp/algorithm/upper_bound

提交回复
热议问题