c++ - 涉及上限和下限的问题

标签 c++

在排序数组中查找给定数字的最后一次和首次出现的位置。如果数字不存在,则将上下边界打印为-1。
我编写了如下代码,但是我无法通过所有测试用例。谁能告诉我为什么?

#include <iostream>
#include<vector>
#include<algorithm>
using namespace std;

int main()
{
    vector<int> v;
    int n,num,q,find;
    cin>>n;
    v.reserve(n);

    for(int i=0;i<n;i++){
        cin>>num;
        v.push_back(num);
    }
    sort(v.begin(),v.end());
    cin>>q;

    while(q--){
        cin>>find;
        auto lb=lower_bound(v.begin(),v.end(),find);
        auto ub=upper_bound(v.begin(),v.end(),find);

        if(lb==v.end() || v.empty()){
            cout<<-1<<" "<<-1<<endl;
        }

        else{
            cout<<lb-v.begin()<<" "<<ub-v.begin()-1<<endl;
        }
    }

    return 0;
}

最佳答案

顾名思义,std::lower_bound(first, last, value)找不到等于value的元素,而是找到lower bound(不小于value的第一个元素)。例如,对于范围1 3 5和目标值2,它将返回指向3的迭代器。

要检查元素是否存在于数组中,可以编写

auto pos = std::lower_bound(first, last, value);
if (pos != last && *pos == value)
    // ...

还应注意,对std::lower_boundstd::upper_bound的两个调用可以替换为对 std::equal_range 的单个调用。

关于c++ - 涉及上限和下限的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61439663/

相关文章:

c++ - 当 C++ 中的数组大小未知时,如何在运行时将对字符串数组的引用作为函数参数传递?

python - 在 python openCV 中一次将许 multimap 像读入内存

c++ - 我在叫什么?

c++ - 使用自动变量打印 vector 的内容

c++ - 为什么这个类型转换模棱两可?

c++ - 真正测试std::atomic是否无锁

c++ - QTableView 添加项目崩溃

c++ - C - Windows 函数(套接字)的编译错误

c++ - 分割字符串

c++ - 计算器.cpp :48:24: error: invalid conversion from 'char' to 'const char*' [-fpermissive]