[英]With a STL map/set/multiset/multimap, How to find the first value greater than or equal to the search key?
Suppose I have a set of values, stored in a std::set: 假设我有一组值,存储在std :: set中:
{1, 2, 6, 8} {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. 我有一个搜索键,比方说,3。我想将3放入一个函数并获得大于或等于3的第一个值,在这种情况下我想得到6。
The find() function provided in map/set/multimap/and set will, of course, return the end iterator for this case. 当然,map / set / multimap /和set中提供的find()函数将返回此情况的结束迭代器。 Is there a similar function to find that would return 6 in this case?
在这种情况下是否有类似的函数可以返回6?
Yes: upper_bound(X)
returns an iterator pointing to the first element greater than X
. 是:
upper_bound(X)
返回指向大于X
的第一个元素的迭代器。 There is also a lower_bound(X)
function which returns an iterator pointing to the first element not less than X
. 还有一个
lower_bound(X)
函数,它返回一个指向不小于X
的第一个元素的迭代器。 Thus, all of the elements in the half-open interval [lower_bound(X), upper_bound(X))
will be equal to X. 因此,半开区间
[lower_bound(X), upper_bound(X))
中的所有元素将等于X.
You want the upper_bound function. 你想要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.
Oops, I meant lower_bound , the member function, not the algorithm. 哎呀,我的意思是lower_bound ,成员函数,而不是算法。
If there's nothing in the set that's greater than or equal to your search item, it will return end(). 如果集合中没有任何内容大于或等于您的搜索项目,它将返回end()。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.