Returning the greatest key strictly less than the given key in a C++ Map

后端 未结 5 1886
伪装坚强ぢ
伪装坚强ぢ 2020-12-16 10:54

Is there a way the C++ STL Maps support this, since lower_bound and upper_bound on maps strictly return the value greater than the passed value.

Lower key

U

5条回答
  •  一向
    一向 (楼主)
    2020-12-16 11:14

    I always find to compute floor(x) and ceil(x) to be patricularly useful

    floor(x) -> greatest element <=x 
    ceil(x) -> smallest element >= x
    
    floor_it = m.lower_bound(x); 
    if (floor_it != m.end() && floor_it->first != x)
          --floor_it;
    
    ceil_it = m.upper_bound(x);
    if (ceil_it != m.end() && (ceil_it-1)->first == x)
        --ceil_it; 
    

提交回复
热议问题