c++ - 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 值。
解决方案
这个例子没有std::lower_bound
正确使用。如果comp
是使用的比较器并且value
是搜索的值,则所有元素comp(element, value) == true
必须comp(element, value) == false
在范围内的所有元素之前。在显示的任何调用中都不是这种情况。
此外,如果第一个参数小于第二个参数,则比较器应该返回 true,而如果第一个元素等于第二个参数,则显示的函数返回 true。这本身并没有被严格禁止,但它可能不会产生预期的结果。
推荐阅读
- reactjs - 使用 combineReducer 时如何在 Redux 中使用单个警报存储
- ios - react-native cli 出现错误 65,Xcode 抛出错误
- html - Angular,html模板中的对象始终为空
- javascript - 如何使 Owl 轮播将列表项渲染为元素?
- netcdf - NetCDF 变量包含不匹配的纬度
- android - 如何用自定义可绘制对象替换默认密码掩码,最后一个字符有延迟?
- google-apps-script - 隐藏和取消隐藏列切换按钮
- javascript - Yii2 使用 Ajax 请求更新表
- postgresql - 创建临时表,插入其中,然后在 pgsql 函数中从中选择
- php - 根据登录用户的电子邮件限制 wordpress 中的页面访问