使用 std::upper_bound 检索向量索引,索引超出范围

Retrieving index of vector using std::upper_bound, index out of bounds

我正在尝试使用 std::upper_bound 根据向量的值检索向量的索引。但出于某种原因,以下代码将 tmpKey 设置为 2,而我的预期值为 1。有什么特别严重的错误吗?

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();
}

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.

向量中没有大于 30 的元素,因此返回结束迭代器。

要获得预期值,您可以使用 std::lower_bound

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.

记得

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.