在向量中找到最接近的值 [英] Find Closest Value in Vector
问题描述
我要完成的工作是遍历一个double值的向量,并返回最接近的double的向量位置.我对此有两个问题.
What I am trying to accomplish is iterating through a vector of double values and returning the vector position of the closest possible double. I am having two issues with this.
-
当尝试使用
lower_bound()
在向量中找到最接近的双精度值时,如果我输入1,则仅会收到零以外的值.
When attempting to find the closest double value in the vector using
lower_bound()
, i only receive a value other than zero if I enter 1.
我不确定如何使用lower_bound
返回矢量位置而不是双精度值.
I am not sure how to use lower_bound
to return a vector position instead of a double value.
这是我正在使用尝试的代码的三个主要文件
Here is my three main files I am using with attempted code
Convert.cpp
Convert.cpp
double Convert::convertmVtoK(double value)
{
double conversion = *std::lower_bound(mV.begin(), mV.end(), value);
cout<<"This is conversion mV to K"<<" "<< conversion;
}
double Convert::convertKtomV(double value)
{
double conversion = *std::lower_bound(mV.begin(), mV.end(), value);
cout<<"This is conversion K to mV"<<" "<< conversion;
}
Conversion.h
Conversion.h
class Convert
{
public:
Convert();
virtual ~Convert();
double convertmVtoK(double mV);
double convertKtomV(double K);
void readFile();
protected:
private:
std::ifstream inFile;
std::vector<double> kelvin,mV,sensitivity;
double tempKelvin,tempmV,tempSensitivity;
};
#endif // CONVERT_H
Main.cpp
#include "Convert.h"
#include <stdio.h>
#include<fstream>
#include<iostream>
int main()
{
Convert convert;
convert.readFile();
convert.convertmVtoK(2.0);
convert.convertKtomV(5.000);
return 0;
}
更新:所以我仍在尝试使用lower_bound().这是我更新的功能.
Update: So I am still attempting to use lower_bound(). Here is my updated function.
double Convert::convertmVtoK(double value)
{
std::vector<double>::iterator pos;
pos = std::lower_bound(mV.begin(), mV.end(), value);
cout<<"This is conversion mV to K"<<" "<< kelvin[(pos-mV.begin())];
}
当前,如果我输入一个浮点值,我仍然无法接收正确的矢量值,它将返回0或[0]矢量值.
Currently the if I input a float value I am still not able to recieve the correct vector value, it either returns 0 or the [0] vector value.
更新2:文本值
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
1.9 1.636600 -18.3
2.0 1.634720 -19.3
2.1 1.632740 -20.3
推荐答案
您可以使用 min_element
和一个比较器,该比较器考虑了到value
的距离:
// precondition: mV is not empty
double get_closest(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());
return *it;
}
这篇关于在向量中找到最接近的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!