[英]With a STL map/set/multiset/multimap, How to find the first value greater than or equal to the search key?
[英]Binary search to find less or equal value in STL C++ multiset
我們有STL(標准模板庫)多集,我們想實現一個二進制搜索,該搜索將給我們第一個小於或等於某個值x的元素
從這篇文章: lower_bound == upper_bound ,我們看到我們可以使用標准的lower_bound和upper_bound來查找與x相比更大的值,而查找較小或相等的東西。
有可能這樣做嗎?
只需使用multiset
的upper_bound
成員函數。 upper_bound
將返回比要搜索的值更大的第一個元素。 這意味着之前的迭代器將是等於或小於該值的第一個元素。 所以在
int main()
{
std::multiset<int> ms = {1,1,2,2,3,3,4,4,5,5};
auto end = ms.upper_bound(3);
for (auto it = ms.begin(); it != end; ++it)
std::cout << *it;
}
它將打印112233
因為那是所有小於或等於3
的元素。
當然,您將需要確保upper_bound
不返回begin()
,這意味着沒有小於或等於您要搜索的元素。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.