温馨提示×

c++中lower_bound函数怎么使用

c++
小亿
106
2024-02-28 14:50:19
栏目: 编程语言

在 C++ 中,lower_bound 函数用于返回在已排序的区间中,第一个不小于给定值的元素的位置。

下面是 lower_bound 函数的语法:

std::vector<int>::iterator lower_bound (std::vector<int>::iterator first, std::vector<int>::iterator last, const int& val);

在使用 lower_bound 函数时,首先需要确保区间已经按照升序排序。然后传入函数三个参数:指向区间起始位置的迭代器 first,指向区间末尾位置的迭代器 last,以及要查找的值 val

lower_bound 函数会在指定区间内搜索不小于给定值 val 的第一个元素,并返回指向该元素的迭代器。如果找不到符合条件的元素,则返回指向区间末尾的迭代器 last

以下是一个简单的示例代码,演示如何使用 lower_bound 函数:

#include <iostream>
#include <vector>
#include <algorithm>

int main() {
    std::vector<int> vec = {1, 2, 3, 4, 5, 6, 7, 8, 9};

    // 查找不小于 5 的第一个元素的位置
    std::vector<int>::iterator it = std::lower_bound(vec.begin(), vec.end(), 5);

    if (it != vec.end()) {
        std::cout << "第一个不小于5的元素位置为:" << std::distance(vec.begin(), it) << std::endl;
    } else {
        std::cout << "未找到符合条件的元素" << std::endl;
    }

    return 0;
}

在上面的示例中,lower_bound 函数会在 vec 中查找不小于 5 的第一个元素,因为 vec 已经是升序排序的,所以返回的迭代器指向 5。

0