map的low_bound怎么用
时间: 2024-05-11 16:19:35 浏览: 11
`lower_bound` 是 `map` 容器的成员函数,用于查找第一个大于或等于给定键值的元素的迭代器。
其函数原型如下:
```c++
iterator lower_bound (const key_type& k);
const_iterator lower_bound (const key_type& k) const;
```
其中,`k` 为要查找的键值,函数返回一个迭代器,指向第一个大于或等于 `k` 的元素。如果不存在这样的元素,则返回指向 `map` 容器的 `end()` 迭代器。
示例代码:
```c++
#include <iostream>
#include <map>
int main() {
std::map<int, int> mp = {{1, 10}, {2, 20}, {3, 30}, {4, 40}, {5, 50}};
std::map<int, int>::iterator it = mp.lower_bound(3); // 查找第一个大于或等于 3 的元素
if (it != mp.end()) {
std::cout << "The element with key " << it->first << " has value " << it->second << '\n';
}
return 0;
}
```
输出结果:
```
The element with key 3 has value 30
```
注意,`lower_bound` 的时间复杂度为 $O(\log n)$,因为它使用二分查找算法实现。