![](/img/trans.png)
[英]using lower_bound or upper_bound on Structure in C++
[英]why C++ lower_bound() allows return pointer equivalent to val while upper_bound() does not
我閱讀了C ++ upper_bound()函數和lower_bound()函數的說明。 對我來說有趣的是,upper_bound()僅返回值> val的第一個迭代器(如果找不到val,則返回范圍[first,last)的最后一個迭代器)。
該實現與lower_bound()不同,盡管它返回的第一個迭代器NOT SMALLER而不是val,所以它允許返回指針等於val。
我只是很好奇地知道以這種方式設計upper_bound()的目的是什么,upper_bound()一定不能返回值等於val的迭代器?
例如:
vector<int> a = {1, 2, 3, 4};
auto i = lower_bound(a.begin(), a.end(), 2); // i is iterator at 2;
auto j = upper_bound(a.begin(), a.end(), 2); // j is iterator at 3;
在C ++中,迭代器通常成對工作。 第一個迭代器指向要考慮的第一個元素,最后一個迭代器指向要考慮的倒數第二個元素。 這是為了使循環變得容易:
for(it cur=first; cur!=last; cur++)
這樣, lower_bound
和upper bound
在一起,形成一個“等於您搜索的項的所有元素的范圍內。在相同范圍std::equal_range
回報。
upper_bound
在諸如std::multimap
情況下很有用,在這種情況下,值按排序順序存儲。 它使您可以在可以由lower_bound
決定起始位置,由upper_bound
決定結束於此位置的范圍內移動。
for (iter_type it = myMap.lower_bound("key_val"); it != myMap.upper_bound("key_val"); it++)
這個for
循環將遍歷直到key == key_val
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.