如何比较 vector<float> 和 float*
How to compare vector<float> and float*
我需要比较两个浮点数组的值是否相等。我知道它们的长度相同。但不幸的是,数组不是同一类型:
bool compare(vector<float> A, float* B)
{
// what do I write here?
}
我该怎么做?我对指针不是很熟悉。
您可以使用 std::equal
来比较范围,即使它们具有不同的类型,如下所示:
bool compare(std::vector<float> A, float* B) // [[ precondition: lengths are the same ]]
{
return std::equal(std::begin(A), std::end(A), B);
}
这取决于大小相同的两个范围,这似乎适用于您的情况。
另请注意,比较 float
值是否完全相等并不是一个好主意。您可能想要使用自定义比较器来检查值是否在一定公差范围内彼此接近。
这是您可以采用的方法。它是从头开始的,所以没有使用外部函数。
bool compare(std::vector<float> A, float* B)
{
float sizeOfBlock = sizeof(B) / sizeof(float) + 1;
if(A.size() == sizeOfBlock)
{
for(int I = 0; I < A.size(); I++)
{
if(A[I] != B[I])
{
return false;
}
}
}
else
{
return false;
}
return true;
}
非常感谢大家!这就是我现在的做法,因为我知道这两个向量具有相同的长度。
bool compareSerAndPar(std::vector<float> Ser, float* Par, int size)
{
float eps = 0.01f;
for(int i = 0; i < size; i++)
{
float temp = fabs(Ser[i] - Par[i]);
if(temp > eps)
{
return false;
}
}
return true;
}
我需要比较两个浮点数组的值是否相等。我知道它们的长度相同。但不幸的是,数组不是同一类型:
bool compare(vector<float> A, float* B)
{
// what do I write here?
}
我该怎么做?我对指针不是很熟悉。
您可以使用 std::equal
来比较范围,即使它们具有不同的类型,如下所示:
bool compare(std::vector<float> A, float* B) // [[ precondition: lengths are the same ]]
{
return std::equal(std::begin(A), std::end(A), B);
}
这取决于大小相同的两个范围,这似乎适用于您的情况。
另请注意,比较 float
值是否完全相等并不是一个好主意。您可能想要使用自定义比较器来检查值是否在一定公差范围内彼此接近。
这是您可以采用的方法。它是从头开始的,所以没有使用外部函数。
bool compare(std::vector<float> A, float* B)
{
float sizeOfBlock = sizeof(B) / sizeof(float) + 1;
if(A.size() == sizeOfBlock)
{
for(int I = 0; I < A.size(); I++)
{
if(A[I] != B[I])
{
return false;
}
}
}
else
{
return false;
}
return true;
}
非常感谢大家!这就是我现在的做法,因为我知道这两个向量具有相同的长度。
bool compareSerAndPar(std::vector<float> Ser, float* Par, int size)
{
float eps = 0.01f;
for(int i = 0; i < size; i++)
{
float temp = fabs(Ser[i] - Par[i]);
if(temp > eps)
{
return false;
}
}
return true;
}