vector 有lower_bound吗
时间: 2023-10-14 14:17:32 浏览: 41
是的,C++标准库中的vector确实有lower_bound函数。lower_bound函数可以在已排序的vector中查找第一个大于或等于给定值的元素,并返回其迭代器。如果没有找到符合条件的元素,则返回vector的end()迭代器。下面是一个示例用法:
```cpp
#include <iostream>
#include <vector>
#include <algorithm>
int main() {
std::vector<int> vec = {1, 2, 3, 4, 5, 6};
auto it = std::lower_bound(vec.begin(), vec.end(), 4);
if (it != vec.end()) {
std::cout << "Found element: " << *it << std::endl;
} else {
std::cout << "Element not found." << std::endl;
}
return 0;
}
```
在上面的示例中,lower_bound函数将返回指向值为4的元素的迭代器。如果要查找的元素不在vector中,lower_bound函数将返回指向第一个大于给定值的元素的迭代器,或者返回end()迭代器。
相关问题
vector的lower_bound函数
vector的lower_bound函数是用来在有序的vector容器中查找第一个大于或等于指定值的元素的迭代器。它的函数原型如下:
```cpp
template <class ForwardIterator, class T>
ForwardIterator lower_bound (ForwardIterator first, ForwardIterator last, const T& val);
```
其中,`first` 和 `last` 是指向容器中一段范围的迭代器,`val` 是要查找的值。lower_bound函数会返回一个迭代器,指向第一个大于或等于val的元素位置。
lower_bound函数的工作原理是使用二分查找算法,在容器的一段范围内查找目标元素。因为容器是有序的,所以可以利用二分查找的特性来提高查找效率。lower_bound函数的返回结果是一个迭代器,可以通过解引用该迭代器来获取查找到的元素的值。
需要注意的是,如果lower_bound函数没有找到大于或等于val的元素,则返回last迭代器。
下面是一个使用lower_bound函数的示例:
```cpp
#include <iostream>
#include <vector>
#include <algorithm>
int main() {
std::vector<int> vec = {1, 2, 3, 4, 5};
auto it = std::lower_bound(vec.begin(), vec.end(), 3);
if (it != vec.end()) {
std::cout << "Found element: " << *it << std::endl;
} else {
std::cout << "Element not found" << std::endl;
}
return 0;
}
```
以上示例中,lower_bound函数会返回指向值为3的元素的迭代器,因为3本身在容器中存在。如果要查找的值不在容器中,lower_bound函数会返回指向大于该值的第一个元素的迭代器,或者返回end()迭代器,表示未找到目标元素。
C++对vector使用lower_bound
C++对vector使用lower_bound可以实现在有序的vector中进行二分查找。lower_bound函数返回一个迭代器,指向第一个不小于给定值的元素。下面是一个示例代码:
```cpp
#include <iostream>
#include <vector>
#include <algorithm>
struct MyStruct {
int value;
};
bool compare(const MyStruct& a, const MyStruct& b) {
return a.value < b.value;
}
int main() {
std::vector<MyStruct> vec = {{1}, {2}, {3}, {4}, {5}};
MyStruct target = {3};
auto it = std::lower_bound(vec.begin(), vec.end(), target, compare);
if (it != vec.end() && it->value == target.value) {
std::cout << "Found at index: " << std::distance(vec.begin(), it) << std::endl;
} else {
std::cout << "Not found" << std::endl;
}
return 0;
}
```
这段代码中,我们定义了一个结构体`MyStruct`,其中包含一个整数成员`value`。我们创建了一个有序的vector,并使用`lower_bound`函数在其中查找`target`结构体。如果找到了匹配的元素,就输出其索引;否则输出"Not found"。