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

前端 未结 5 1739
南方客
南方客 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:40

    std::prev: https://en.cppreference.com/w/cpp/iterator/prev

    #include 
    #include 
    
    int main()
    {
        std::map m{{2, 'a'}, {4, 'b'}, {6, 'c'}, {8, 'd'}, {10, 'e'}};
    
        int num = 3;
        auto it = m.upper_bound(num);
        auto pv = std::prev(it);
    
        std::cout << "upper bound of " << num << ": "
            << it->first << ", " << it->second << '\n';
        std::cout << "lower than or equal of " << num << ": "
            << pv->first << ", " << pv->second << '\n';
    }
    

    Output:

    upper bound of 3: 4, b
    lower than or equal than 3: 2, a
    

提交回复
热议问题