使用STL的map/set/multiset/multimap,如何找到第一个大于或等于搜索键的值?

发布于 2024-07-06 23:51:51 字数 211 浏览 6 评论 0原文

假设我有一组值,存储在 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

酒废 2024-07-13 23:51:53

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().

病女 2024-07-13 23:51:52

您需要 upper_bound 函数。

map<int, int> mymap = { 1,2,6,8 };
map<int,int>::iterator i = mymap.upper_bound(3); // returns an iterator to the '6' element.

You want the upper_bound function.

map<int, int> mymap = { 1,2,6,8 };
map<int,int>::iterator i = mymap.upper_bound(3); // returns an iterator to the '6' element.
只是偏爱你 2024-07-13 23:51:52

是: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 than X. There is also a lower_bound(X) function which returns an iterator pointing to the first element not less than X. Thus, all of the elements in the half-open interval [lower_bound(X), upper_bound(X)) will be equal to X.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文