STL新手问题:
关于函数std::map::upper_bound
和std::map::lower_bound
,指定Map中实际上不存在的键是否有效?
示例
std::map<int,int> intmap;
std::map<int,int>::iterator it1, it2;
intmap[1] = 10;
intmap[2] = 20;
intmap[4] = 40;
intmap[5] = 50;
it1 = intmap.lower_bound (3); // Is this valid?
it2 = intmap.upper_bound (3); // Is this valid?
2条答案
按热度按时间ddhy6vgd1#
是的,它们都有效。
map::lower_bound
返回指向第一个不小于key的元素的迭代器。map::upper_bound
返回指向第一个大于key的元素的迭代器。lower_bound/upper_bound
返回插入值的位置。注意,如果你想检查key值是否是map,你可以使用std::map::find
sf6xfgos2#
如果有unordered_map,我们可以使用
mp.lower_bound(k) - mp.begin()
找到count。@humam-helfawi
mp.lower_bound(k) - mp.begin()
不会给予元素的计数,因为stl::map
中的底层数据结构是tree
。在树中,不能通过从
mp.begin()
中减去来找到count。观想一次,你就会明白。