就像标题所说的那样,我正在尝试使用二分搜索方法来搜索排序向量中最接近的给定值并返回其索引。我尝试使用 lower/upper_bound() 但返回的值是第一个或最后一个向量值,或者“0”。下面是我已将温度和电压读入向量的 txt 文件。
1.4 1.644290 -12.5
1.5 1.642990 -13.6
1.6 1.641570 -14.8
1.7 1.640030 -16.0
1.8 1.638370 -17.1
Run Code Online (Sandbox Code Playgroud)
这是我当前有效的线性搜索
double Convert::convertmVtoK(double value) const
{
assert(!mV.empty());
auto it = std::min_element(mV.begin(), mV.end(), [value] (double a, double b) {
return std::abs(value - a) < std::abs(value - b);
});
assert(it != mV.end());
int index = std::distance(mV.begin(), it);
std::cout<<kelvin[index];
return kelvin[index];
}
Run Code Online (Sandbox Code Playgroud)
这是我目前正在努力提高性能的算法。
double Convert::convertmVtoK(double value)
{
auto it = lower_bound(mV.begin(), mV.end(), value);
if (it == mV.begin())
{
it = mV.begin();
}
else …Run Code Online (Sandbox Code Playgroud)