Linux 拨号vps windows公众号手机端

c++中upper_bound的用法是什么

lewis 9年前 (2016-08-12) 阅读数 12 #程序编程
文章标签 c++

在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()。

版权声明

本文仅代表作者观点,不代表米安网络立场。

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

热门