简体   繁体   English

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

[英]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.

lower_bound . lower_bound

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.

相关问题 如何找到小于设置了STL的搜索键的第一个值? - How to find the first value less than the search key with STL set? 二进制搜索以查找STL C ++多集中的更少或相等的值 - Binary search to find less or equal value in STL C++ multiset 如何找到键大于val的地图的第一个元素 - How can I find the first element of a map where key is greater than val 如何找到小于或等于X的最大值和大于或等于X的最小值? - How do I find the largest value smaller than or equal to X and the smallest value greater than or equal to X? STL排序向量找到小于或等于给定值的第一个元素 - STL sorted vector find first element less than or equal to given value 如果第一位小数大于或等于5,如何对数字+1? - How to +1 to the digit if the first decimal is greater than or equal to 5? 从地图容器中查找大于用户指定值的第一个值 - Find the first value greater than user specified value from a map container 使用STL映射查找对中第一个元素的最低密钥对 - Find the lowest key pair for the first element in the pair using STL Map 查找功能不能被多集stl识别 - find function not recognized by a multiset stl std :: multimap <key,value>和std :: map <key,std :: set <value >>之间有什么区别? - What's the difference between std::multimap<key, value> and std::map<key, std::set<value> >
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM