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

问题描述 投票: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
1个回答
0
投票

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

<algorithm>

您正在寻找

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

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