Search code examples
c++lower-bound

Lower_bound gives other result


testing lower_bound function in c++ Im getting weird result after running this code in Ideone. What am I doing wrong? is auto usage correct here?

code :

    vector<int> a(5);
    a.clear();
    rep(i,0,5){
        a[i]=i+1;
        cout<<a[i]<<' ';
        }
    cout<<endl;
    auto pos = lower_bound(a.begin(),a.end(),3);
    cout<< (pos-a.begin())<<'\n';

output :

1 2 3 4 5 
0

Why?? expected output :

2

What am I doing wrong I don't understand. seems like basic C++ code


Solution

  • This line creates a vector of five elements:

    vector<int> a(5);
    

    Next line removes all the five elements, setting the size to zero:

    a.clear();
    

    Consequently the loop writes beyond the end() of the vector, triggering undefined behavior. This does not expand the vector.

    In practice you call lower_bound on an empty sequence, so pos == a.begin(). Remove the call to clear() in order to fix the problem.