1. lower_bound
的查找范围
std::lower_bound
在已排序的序列中查找第一个大于或等于给定值的元素。其查找范围是 [first, last),即包含 first
,但不包含 last
。
2. make_pair()
匹配查找数据类型
在使用 std::lower_bound
查找 std::pair
类型的元素时,需要确保 make_pair()
创建的 pair
的数据类型与容器中的元素类型匹配。
3. 示例
#include <iostream>
#include <vector>
#include <algorithm>
int main() {
std::vector<std::pair<int, std::string>> vec = {
{1, "apple"},
{2, "banana"},
{3, "cherry"},
{4, "date"}
};
// 查找第一个大于等于 (2, "") 的元素
auto it = std::lower_bound(vec.begin(), vec.end(), std::make_pair(2, std::string("")));
if (it != vec.end()) {
std::cout << "Found: " << it->first << ", " << it->second << std::endl; // 输出: Found: 2, banana
} else {
std::cout << "Not found" << std::endl;
}
return 0;
}
3.1. 说明
std::lower_bound
返回一个迭代器,指向查找范围内第一个大于或等于给定值的元素。- 如果查找失败,返回
last
。 make_pair(2, std::string(""))
创建一个pair
,其first
成员为 2,second
成员为空字符串。- 需要确保
pair
的类型与容器中的元素类型匹配。
4.例题
vector<int> findRightInterval(vector<vector<int>>& intervals) {
vector<pair<int, int>> starts; // {start, index}
for(int i = 0; i < intervals.size(); i++) {
starts.emplace_back(intervals[i][0], i);
}
sort(starts.begin(), starts.end());
vector<int> res;
for(auto& interval : intervals) {
// 查找第一个start >= interval[1]的区间
auto it = lower_bound(starts.begin(), starts.end(), make_pair(interval[1], 0));
if(it != starts.end()) {
res.push_back(it->second);
} else {
res.push_back(-1);
}
}
return res;
}