c++ pair lower_bound
时间: 2025-07-06 13:52:04 浏览: 13
### C++ 中 `std::pair` 和 `std::lower_bound` 的用法
#### 使用 `std::pair`
在 C++ 中,`std::pair` 是标准库提供的一种容器适配器,用于存储两个不同类型的数据。定义如下:
```cpp
#include <utility>
// 定义一对 int 和 double 类型的 pair
std::pair<int, double> p(10, 3.14);
```
可以通过成员函数 `.first` 和 `.second` 板访问这对数据中的第一个和第二个元素。
#### 使用 `std::lower_bound`
`std::lower_bound` 函数位于 `<algorithm>` 头文件中,用于在一个已排序序列中找到不小于给定值的第一个位置。对于自定义类型的比较,可以传递第三个参数作为比较函数对象或 lambda 表达式。
当与 `std::pair` 结合使用时,通常会涉及到基于 `pair.first` 或者其他条件来执行二分查找操作。
下面是一个具体的例子展示如何结合两者一起工作:
假设有一个由整数键及其对应字符串组成的有序列表,并希望快速定位某个特定范围内的起始点。
```cpp
#include <iostream>
#include <vector>
#include <map>
#include <utility>
#include <algorithm>
int main() {
std::vector<std::pair<int, std::string>> vec = {
{1,"one"},{2,"two"},{3,"three"},
{5,"five"},{8,"eight"}
};
auto it = std::lower_bound(vec.begin(), vec.end(),
std::make_pair(4, ""),
[](const std::pair<int,std::string>& a,
const std::pair<int,std::string>& b){
return a.first < b.first;
});
if(it != vec.end()){
std::cout << "Found at position: "
<< (*it).first << ", value="
<< (*it).second << '\n';
} else {
std::cout << "Not found\n";
}
return 0;
}
```
这段代码创建了一个包含若干个 `std::pair<int, string>` 对象的向量,并通过 `std::lower_bound()` 查找不低于指定数值的位置。这里特别注意的是,在调用 `std::lower_bound()` 方法时传入了自定义的比较谓词以便按照 `pair.first` 进行升序排列[^1]。
阅读全文
相关推荐



















