在C ++ Map中返回严格小于给定键的最大键 [英] Returning the greatest key strictly less than the given key in a C++ Map

查看:787
本文介绍了在C ++ Map中返回严格小于给定键的最大键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

C ++ STL Maps支持这种方式,因为在映射上的lower_bound和upper_bound严格返回大于传递值的值。

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.

电源键

使用案例我有一个有时间作为键的地图以排序的方式,所以在MAP

Use case I have a map with times as keys in a sorted manner so in a MAP

time t1   = value1
time t2   = value2
time t2.5 = value3

我传递给这个MAP t2.3,那么它应该给我value2。在地图上做一个lower_bound,并返回一个等于返回最大键严格小于给定键的元素,即

In this case if I pass to this MAP t2.3 then it should give me value2. Does doing a lower_bound on the map and going back one element equivalent to the "returning greatest key strictly less than given key" i.e

iterator = map.upper_bound(2.3)
and then 
iterator--;


推荐答案

可以使用lower_bound,以前看过它,并使用它像这样。

Yeah, lower_bound can be used for that, i've seen it before and used it like that.

map_type::iterator it = map.lower_bound(2.3);
if(it != map.begin()) {
    --it;
    // it now points at the right element
}

最大,但更小(如果它!= map.begin()是真的)一。如果是在.begin,那么没有更小的密钥。从注释的好主意是返回 .end 如果没有元素,并把这个东西包装到一个函数:

Would actually return the greatest, yet smaller (if it != map.begin() was true) one. If it was at .begin, then there is no smaller key. Nice idea from the comments is to return .end if there is no element that's less and pack this stuff into a function:

template<typename Map> typename Map::const_iterator 
greatest_less(Map const& m, typename Map::key_type const& k) {
    typename Map::const_iterator it = m.lower_bound(k);
    if(it != m.begin()) {
        return --it;
    }
    return m.end();
}

template<typename Map> typename Map::iterator 
greatest_less(Map & m, typename Map::key_type const& k) {
    typename Map::iterator it = m.lower_bound(k);
    if(it != m.begin()) {
        return --it;
    }
    return m.end();
}

模板应该适用于 std :: set

这篇关于在C ++ Map中返回严格小于给定键的最大键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆