c++ - upper_bound 并找到不同的结果

标签 c++ vector stl

我是 STL 的新手,在 vector 上使用了 find()upper_bound() 函数来找到 6 的位置。代码如下


#include <bits/stdc++.h>

using namespace std;

int main()
{
    vector<int> sam ={1,2,5,3,7,8,4,6};
    int f=upper_bound(sam.begin(), sam.end(), 6)- sam.begin();

    vector<int>::iterator it; 
    it =find (sam.begin(), sam.end(), 6);
    int d=it - sam.begin() ;
    cout<<d<<" "<<f<<endl;

    return 0;
}

运行代码时的输出是 7 4 ,而我预计它是 7 7 。 我做错了什么?

最佳答案

cppreference.com for std::upper_bound() 解释得很好(强调我的):

Returns an iterator pointing to the first element in the range [first, last) that is greater than value, or last if no such element is found.

The range [first, last) must be partitioned with respect to the expression !(value < element) or !comp(value, element), i.e., all elements for which the expression is true must precede all elements for which the expression is false. A fully-sorted range meets this criterion.

在您的例子中,您有一个 7(大于 6,在索引 4 处)出现在 4(等于或小于 6)之前,因此不满足先决条件。 p>

std::upper_bound()的想法它的同伴是在排序数组中快速进行二进制搜索。与 std::find() 中的线性搜索相反,它只需要 O(log(n)) 的时间复杂度而不是 O(n)。

关于c++ - upper_bound 并找到不同的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56011151/

相关文章:

c++ - 将容器中的基类向下转换为派生类

c++ - 标准 vector 之上的 C++11 包装器类

c++ - 在C++11中如何表达普通的存储(导出)和加载(导入)屏障(fence)?

c++ - 尝试链接 .cpp 文件时出现多重定义错误(头文件中没有 .cpp)

c++ - 在指向(全局/持久)对象的指针超出范围后,对象(不是指针)的成员 vector 获取 'unset'

c++ - 设置 vector 等于{};

c++ - 如何查找二维 vector 是否包含重复行?

c++ - 强制 std::string 使用 unsigned char(0 到 255)而不是 char(-128 到 127)

c++ - 从 CMake/clang 警告生成代码气候报告

c++ - 这是否无效 &(*_shmItr) == NULL 其中 _shmItr 是一个列表迭代器