gpt4 book ai didi

c++ - 搜索具有上限和下限的 map

转载 作者:IT老高 更新时间:2023-10-28 22:02:19 28 4
gpt4 key购买 nike

STL新手问题:

关于函数 std::map::upper_boundstd::map::lower_bound 指定映射中实际不存在的键是否有效?

例子

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?

最佳答案

是的,它们都是有效的。

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 返回值将被插入的位置。

注意,如果要检查 value 键是否为 map,可以使用 std::map::find

关于c++ - 搜索具有上限和下限的 map ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19158198/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com