lower_bound returns lowest element >= value.
upper_bound returns lowest element > value.
If value is > all values in the vector then both will return end().
If the exact value doesn't exist then the iterators returned from lower_bound and upper_bound will be the same; i.e., they will both be the lowest element > value (or end()).
If the exact value does exist, then they will be different. The lower_bound iterator will be the lowest positioned element that equals the value; the upper_bound iterator will be one past the last element that equals the value (possibly end()). That way you can find a group of equal elements. In your case since you have no duplicates that doesn't apply so there's no point using both.
However, using lower_bound as you are doing is not quite right, either. And you don't need to convert the iterator to an index to access the value. You can "dereference" the iterator with *it. But if the value you searched for is greater than the highest value, lower_bound will return end(), which can't be dereferenced.
Here's an example that returns the value that is closest to the value you are looking for.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
|
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int search(vector<int> &v, int value)
{
auto it = lower_bound(v.begin(), v.end(), value);
if (it == v.end())
return v.back(); // return last element
auto found = *it;
if (it != v.begin())
{
auto found2 = *(--it);
if (abs(value - found2) < abs(value - found))
found = found2;
}
return found;
}
int main()
{
vector<int> v {3, 5, 9, 12, 13, 15};
std::cout << search(v, 1) << '\n'; // 3
std::cout << search(v, 10) << '\n'; // 9
std::cout << search(v, 11) << '\n'; // 12
std::cout << search(v, 99) << '\n'; // 15
}
| |
But note that the searched for value could be much less than the lowest or much greater than the highest, so it's hard to see the relevance of returning the corresponding value. Why wouldn't you use an equation for this? What exactly are you trying to accomplish?