[英]custom comparator in lower_bound() stl function in c++
[英]Custom comparator in lower_bound() STL
我試圖了解比較器如何在 lower_bound 函數中工作,我遇到了這個例子:
#include <vector>
#include <algorithm>
using namespace std;
bool ignore_case(char a, char b) {
return(tolower(a) == tolower(b));
}
int main(void) {
vector<char> v = {'A', 'b', 'C', 'd', 'E'};
auto it = lower_bound(v.begin(), v.end(), 'C');
cout << "First element which is greater than \'C\' is " << *it << endl;
it = lower_bound(v.begin(), v.end(), 'C', ignore_case);
cout << "First element which is greater than \'C\' is " << *it << endl;
it = lower_bound(v.begin(), v.end(), 'z', ignore_case);
cout << "All elements are less than \'z\'." << endl;
return 0;
}
以下代碼的output為:
First element which is greater than 'C' is b
First element which is greater than 'C' is d
All elements are less than 'z'.
相等檢查的自定義比較器如何工作? 我認為如果 a 應該在 b 之前它返回 true,反之則返回 false。 它在 lower_bound() 函數中是如何工作的,它應該檢索大於等於我們給定鍵的 FIRST 值。
此示例未正確使用std::lower_bound
。 如果comp
是使用的比較器並且value
是搜索的值,則comp(element, value) == true
的所有元素必須在范圍內comp(element, value) == false
的所有元素之前。 在顯示的任何調用中都不是這種情況。
此外,如果第一個參數小於第二個參數,比較器應該返回 true,而顯示的 function 如果第一個元素等於第二個參數,則返回 true。 這本身並沒有被嚴格禁止,但它可能不會產生預期的結果。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.