0

I am attempting to retrieve a vector's index based on it's value using std::upper_bound. For some reason though, the following code sets tmpKey equal to 2 vs my expected value of 1. Does anything stick out as being horribly wrong?

int main()
{
    float time = 30.0000000;
    std::vector<float> positionKeyTimes = { 0.000000000, 30.0000000 };

    auto it = std::upper_bound(positionKeyTimes.begin(), positionKeyTimes.end(), time);
    auto tmpKey = (size_t)(it - positionKeyTimes.begin());

    std::cout << tmpKey << "\n";

    std::cin.get();
}
whitwhoa
  • 2,389
  • 4
  • 30
  • 61

1 Answers1

2

std::upper_bound

Returns an iterator pointing to the first element in the range [first, last) that is greater than value, or last if no such element is found.

There's no element greater than 30 in your vector, so the end iterator is returned.

To get your expected value you could use std::lower_bound instead, which

Returns an iterator pointing to the first element in the range [first, last) that is not less than (i.e. greater or equal to) value, or last if no such element is found.

Remembering that

The range [first, last) must be partitioned with respect to the expression element < value or comp(element, value), i.e., all elements for which the expression is true must precede all elements for which the expression is false. A fully-sorted range meets this criterion.

Bob__
  • 12,361
  • 3
  • 28
  • 42
  • That makes sense. So is it true that the begin() iterator would have an index of 1 and the end() iterator would have an index of the size of the element? I was under the impression begin() was zero and end() was size - 1. – whitwhoa May 06 '20 at 23:13
  • @whitwhoa No, the index corresponding to end() is size. See e.g. this [example](https://godbolt.org/z/6xpop4). – Bob__ May 06 '20 at 23:51