如何为std::lower_bound()自定义比较函数以仅比较pair的first成员?
让std::lower_bound仅比较pair的.first属性的正确实现
问题根源
你当前的代码失效,核心问题出在自定义比较函数comp上:
std::lower_bound要求比较函数必须定义严格弱序关系,也就是判断「第一个参数是否应该排在第二个参数之前」,而非直接判断相等。- 你用
i.first == value作为比较逻辑,完全不符合lower_bound的工作机制,导致它无法正确定位目标元素。
修正步骤
1. 编写正确的比较函数
将比较函数改为判断pair的.first是否小于目标字符串,同时用const引用避免不必要的拷贝:
bool comp(const pair<string, int>& elem, const string& target) { return elem.first < target; }
2. 确保容器按.first有序(可选但关键)
虽然你提到输入是有序的,但如果实际输入未按pair.first排序,必须先对vector做排序,排序时也要遵循相同的比较逻辑:
sort(books.begin(), books.end(), [](const pair<string, int>& a, const pair<string, int>& b) { return a.first < b.first; });
3. 完整修正代码
#include <iostream> #include <vector> #include <algorithm> using namespace std; // 正确的比较逻辑:判断pair的first是否小于目标字符串 bool comp(const pair<string, int>& elem, const string& target) { return elem.first < target; } int main() { vector<pair<string, int>> books; int n; cin >> n; for(int i = 0; i < n; i++) { string name; int code; cin >> name >> code; books.emplace_back(name, code); // 用emplace_back替代make_pair,更高效 } // 若输入未按书名排序,启用下面的排序代码 sort(books.begin(), books.end(), [](const pair<string, int>& a, const pair<string, int>& b) { return a.first < b.first; }); int m; cin >> m; for(int j = 0; j < m; j++) { string consult; cin >> consult; auto it = lower_bound(books.begin(), books.end(), consult, comp); // 校验是否找到目标元素 if (it != books.end() && it->first == consult) { cout << (it->second == 1 ? "Available" : "Borrowed") << '\n'; } else { cout << "Not found" << '\n'; } } return 0; }
关键说明
std::lower_bound返回的是第一个不小于目标值的元素迭代器(基于比较函数的逻辑),因此找到迭代器后,必须额外判断该元素的.first是否等于目标字符串,避免因存在更大元素而误判。- 比较函数的参数顺序不能颠倒:第一个参数是容器内的元素(pair),第二个是查找的目标值(string),这是lower_bound的强制要求。
内容的提问来源于stack exchange,提问作者Jonas
相关产品推荐
相关产品推荐

