使用STL的map/set/multiset/multimap,如何找到第一个大于或等于搜索键的值?
假设我有一组值,存储在 std::set:
{1, 2, 6, 8}
中,并且我有一个搜索键,例如 3。我想将 3 放入函数中并获得更大的第一个值大于或等于 3,在这种情况下我想要得到 6。map/set/multimap/and
set 中提供的 find() 函数当然会返回这种情况的结束迭代器。 是否有类似的 find 函数在这种情况下返回 6?
Suppose I have a set of values, stored in a std::set:
{1, 2, 6, 8}
and I have a search key, say, 3. I want to put 3 into a function and get the first value greater than or equal to 3, in this case I would want to get 6.
The find() function provided in map/set/multimap/and set will, of course, return the end iterator for this case. Is there a similar function to find that would return 6 in this case?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
lower_bound。
哎呀,我的意思是 lower_bound,成员函数,而不是算法。
如果集合中没有任何内容大于或等于您的搜索项,它将返回 end()。
lower_bound.
Oops, I meant lower_bound, the member function, not the algorithm.
If there's nothing in the set that's greater than or equal to your search item, it will return end().
您需要 upper_bound 函数。
You want the upper_bound function.
是:
upper_bound(X)
返回一个指向第一个大于X
的元素的迭代器。 还有一个lower_bound(X)
函数,它返回一个指向不小于X
的第一个元素的迭代器。 因此,半开区间[lower_bound(X), upper_bound(X))
中的所有元素都将等于X。Yes:
upper_bound(X)
returns an iterator pointing to the first element greater thanX
. There is also alower_bound(X)
function which returns an iterator pointing to the first element not less thanX
. Thus, all of the elements in the half-open interval[lower_bound(X), upper_bound(X))
will be equal to X.