![](/img/trans.png)
[英]How do map::lower_bound() and map::upper_bound work in C++?
[英]How do upper_bound and lower_bound work with comparator in c++?
我只是想知道 C++ 標准庫中的 lower_bound 和 upper_bound 函數如何使用比較器工作。 使用 cppreference.com 提供的文檔,我無法理解它們實際上是如何工作的。 例如。
vector<int> arr = {1, 1, 2, 2, 3, 3, 4, 4, 5, 5};
auto it1 = lower_bound(arr.begin(), arr.end(), 3, less<int>());
auto it2 = lower_bound(arr.begin(), arr.end(), 3, less_equal<int>());
auto it3 = lower_bound(arr.begin(), arr.end(), 3, greater<int>());
auto it4 = lower_bound(arr.begin(), arr.end(), 3, greater_equal<int>());
auto it5 = lower_bound(arr.begin(), arr.end(), 3, equal_to<int>());
auto it6 = lower_bound(arr.begin(), arr.end(), 3, not_equal_to<int>());
// Output in comments
cout << it1 - arr.begin() << endl; // 4
cout << it2 - arr.begin() << endl; // 6
cout << it3 - arr.begin() << endl; // 0
cout << it4 - arr.begin() << endl; // 10
cout << it5 - arr.begin() << endl; // 6
cout << it6 - arr.begin() << endl; // 4
auto it7 = upper_bound(arr.begin(), arr.end(), 3, less<int>());
auto it8 = upper_bound(arr.begin(), arr.end(), 3, less_equal<int>());
auto it9 = upper_bound(arr.begin(), arr.end(), 3, greater<int>());
auto it10 = upper_bound(arr.begin(), arr.end(), 3, greater_equal<int>());
auto it11 = upper_bound(arr.begin(), arr.end(), 3, equal_to<int>());
auto it12 = upper_bound(arr.begin(), arr.end(), 3, not_equal_to<int>());
cout << it7 - arr.begin() << endl; // 6
cout << it8 - arr.begin() << endl; // 4
cout << it9 - arr.begin() << endl; // 10
cout << it10 - arr.begin() << endl; // 0
cout << it11 - arr.begin() << endl; // 4
cout << it12 - arr.begin() << endl; // 6
對於 lower_bound 他們使用: (*it < val) [ (comp(*it, val)) for comparator]
對於上限,他們使用: (,(val < *it)) [ (!comp(val, *it)) for comparator) ]
有人可以解釋他們使用比較器獲得所有所需輸出的工作嗎?
std::lower_bound
要求輸入范圍相對於比較器進行分區——也就是說,所有comp(element, value)
返回true
的元素必須在它返回false
的元素之前。 在您的示例中,只有使用less
和less_equal
的調用才能滿足此要求; 其他調用表現出未定義的行為。
std::upper_bound
要求輸入范圍相對於表達式,comp(value, element)
進行分區 - 同樣,它返回true
的所有元素必須在它返回false
的元素之前。 在您的示例中,只有使用less
和less_equal
的調用才能滿足此要求; 其他調用表現出未定義的行為。
涉及less
和less_equal
的調用按照記錄的方式進行,並產生預期的結果。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.