c++ 用上界和下界搜索一个Map

qxsslcnc  于 2023-03-25  发布在  其他
关注(0)|答案(2)|浏览(144)

STL新手问题:
关于函数std::map::upper_boundstd::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?
ddhy6vgd

ddhy6vgd1#

是的,它们都有效。
map::lower_bound返回指向第一个不小于key的元素的迭代器。
map::upper_bound返回指向第一个大于key的元素的迭代器。

intmap[1]=10;
intmap[2]=20;
intmap[4]=40;   // <<---both lower_bound(3)/upper_bound(3) will points to here
intmap[5]=50;

lower_bound/upper_bound返回插入值的位置。
注意,如果你想检查key值是否是map,你可以使用std::map::find

sf6xfgos

sf6xfgos2#

如果有unordered_map,我们可以使用mp.lower_bound(k) - mp.begin()找到count。
@humam-helfawi mp.lower_bound(k) - mp.begin()不会给予元素的计数,因为stl::map中的底层数据结构是tree
在树中,不能通过从mp.begin()中减去来找到count。
观想一次,你就会明白。

相关问题