温馨提示×

c++中upper_bound的用法是什么

c++
小亿
90
2024-04-19 16:59:09
栏目: 编程语言

在C++中,upper_bound是STL中的一个函数,用于在有序容器(如vector、set、map等)中查找第一个大于给定值的元素的位置。具体用法如下:

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

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

    // 使用upper_bound查找第一个大于4的元素的位置
    std::vector<int>::iterator it = std::upper_bound(v.begin(), v.end(), 4);

    if (it != v.end()) {
        std::cout << "第一个大于4的元素位置为:" << *it << std::endl;
    } else {
        std::cout << "未找到大于4的元素" << std::endl;
    }

    return 0;
}

上面的代码演示了如何使用upper_bound函数在vector中查找第一个大于4的元素的位置。如果找到了符合条件的元素,会返回该元素的迭代器;否则返回end()。

0