如何找到数组中最接近的较小数字?

问题描述 投票:0回答:1

考虑这个数组:

std::vector<int> numbers = { 0, 4, 12, 60, 89 };

已排序且只有正数。

在数组中找到最接近的较小数字(最好是从

<algorithm>
)的最简单方法是什么?示例:

数量 结果
0 0
3 0
15 12
74 60
150 89
c++ arrays algorithm stdvector
1个回答
3
投票

在数组中找到最接近的较小数字的最简单方法是什么,最好是从

<algorithm>

您正在寻找

std::lower_bound
(或自 C++20 起为
std::ranges::lower_bound
)。检查参考页面中给出的示例代码。

例如,您可以编写如下函数:

#include <algorithm>  // std::ranges::lower_bound

auto find_closest(std::vector<int> const& numbers, int query)
{
    auto it = std::ranges::lower_bound(numbers, query);
    // Handle negative values
    return (it == std::cbegin(numbers)) ? *it : *(--it);
}

观看现场演示

我把错误处理留给你。

© www.soinside.com 2019 - 2024. All rights reserved.