【问题标题】:lower_bound function is returning the wrong iteratorlower_bound 函数返回错误的迭代器
【发布时间】:2021-11-02 23:26:11
【问题描述】:

在下面的代码中,7 和 4 都返回相同的值,即 2,同时每个 else 数字都返回正确的索引

#include<iostream>
#include<algorithm>
#include<vector>
using namespace std;
int main(){
    vector<int> v;

    v.push_back(1);
    v.push_back(3);
    v.push_back(7);
    v.push_back(4);
    v.push_back(9);
    cout<<"lower bound : "<<lower_bound(v.begin(),v.end(),7)-v.begin()<<endl;
    cout<<"lower bound : "<<lower_bound(v.begin(),v.end(),4)-v.begin()<<endl;
}

输出:

lower bound : 2
lower bound : 2

我不明白代码有什么问题。

【问题讨论】:

    标签: c++ algorithm vector


    【解决方案1】:

    vector 应该提前排序。例如

    std::sort(v.begin(), v.end());
    cout<<"lower bound : "<<lower_bound(v.begin(),v.end(),7)-v.begin()<<endl; // ->3
    cout<<"lower bound : "<<lower_bound(v.begin(),v.end(),4)-v.begin()<<endl; // ->2
    

    【讨论】:

      【解决方案2】:

      lower_bound 查找大于或等于第三个参数的第一个元素。

      所以lower_bound(v.begin(),v.end(),4) 正确地找到了7

      另一方面,lower_bound(v.begin(),v.end(),4) 会导致未定义的行为,因为您的向量 violates the precondition

      范围[first, last) 必须根据表达式element &lt; valuecomp(element, value) 进行分区,即表达式为真的所有元素必须在表达式为假的所有元素之前。完全排序的范围符合此标准。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-04-29
        • 1970-01-01
        • 1970-01-01
        • 2012-12-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多