infixint943
infixint943

Reputation: 103

Lower bound error

I am following this tutorial on Lower_bound() in C++. I have made a simple code to find a number in a vector lesser than or equal to a number from the vector + any number that I want. My code goes like this

cout << *lower_bound(A.begin(), A.end(), A[x] + 3);

where the vector A[] is sorted. But the code points it to a number greater than the sum of both the numbers.

For example if my vector has values as 0, 3, 5, 8, 12 and I want it to print the nearest number lesser than or equal to A[3] + 3 = 11 it should give output as 8 but it gives the output of 12. Any reasons?

Here is my code:

#include <bits/stdc++.h>
using namespace std;

int main() {
    vector<int> A = {0, 5, 3, 12, 8};

    sort(A.begin(), A.end());
    cout << "A[3] = " << A[3] << endl;
    cout << *lower_bound(A.begin(), A.end(), A[3] + 3) << endl;
    return 0;
}

Upvotes: 1

Views: 849

Answers (2)

Caleth
Caleth

Reputation: 62636

If you want the largest number not greater than your target, you can use std::greater<> and reverse iterators (or sort by std::greater<>)

#include <vector>
#include <iostream>
#include <algorithm>

int main() {
    std::vector<int> A = {0, 5, 3, 12, 8};

    std::sort(A.begin(), A.end());
    std::cout << "A[3] = " << A[3] << std::endl;
    std::cout << *std::lower_bound(A.rbegin(), A.rend(), A[3] + 3, std::greater<int>{}) << std::endl;
    return 0;
}

Upvotes: 0

user9614249
user9614249

Reputation:

lower_bound

Returns an iterator pointing to the first element in the range [first,last) which does not compare less than val.

In your case it is not returning the last value less than 11. It returns the first value not less than 11, which in your example is 12.

Upvotes: 3

Related Questions