function for finding last item less-than-or-equal to, like lower_bound

前端 未结 5 1746
南方客
南方客 2021-01-30 12:52

Is there a function in that uses binary search, like lower_bound but that returns the last item less-than-or-equal-to according to a given predic

5条回答
  •  终归单人心
    2021-01-30 13:51

    I have test your reverse iterator solution, it is correct.

    Given v is sorted by '<'

    Find last element less than x:

    auto iter = std::upper_bound(v.rbegin(), v.rend(), x, std::greater());
    if(iter == v.rend())
        std::cout<<"no found";
    else
        std::cout<<*iter;
    

    Find last element less than equal x:

    auto iter = std::lower_bound(v.rbegin(), v.rend(), x, std::greater());
    if(iter == v.rend())
        std::cout<<"no found";
    else
        std::cout<<*iter;
    

    This is better than iter -= 1 version

提交回复
热议问题