首页 > 解决方案 > 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;  
}  

以下代码的输出是:

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 值。

标签: c++stl

解决方案


这个例子没有std::lower_bound正确使用。如果comp是使用的比较器并且value是搜索的值,则所有元素comp(element, value) == true必须comp(element, value) == false在范围内的所有元素之前。在显示的任何调用中都不是这种情况。

此外,如果第一个参数小于第二个参数,则比较器应该返回 true,而如果第一个元素等于第二个参数,则显示的函数返回 true。这本身并没有被严格禁止,但它可能不会产生预期的结果。


推荐阅读