在C++中查找两个向量之间最相似的值

find the most similar value between two vectors in C++

本文关键字:之间 向量 相似 两个 C++ 查找      更新时间:2023-10-16

我有两个排序向量,我想找到 vector1 中与 vector2 中另一个值差异(距离(最小的值的索引。但是,我的以下代码可以完成这项工作,因为我使用的向量总是排序的,我觉得还有另一种更有效的方法来做同样的事情。有导游吗?提前谢谢。

#include<iostream>
#include<cmath>
#include<vector>
#include<limits>
std::vector<float> v1{2,3,6,7,9};
std::vector<float> v2{4,6.2,10};
int main(int argc, const char * argv[]) 
{    
float mn=std::numeric_limits<float>::infinity();
float difference;
int index;
for(int i=0; i<v1.size(); i++){
for(int j=0; j<v2.size(); j++){
difference = abs(v1[i]-v2[j]);
if(difference < mn){
mn= difference;
index = i;
}
}
}
std::cout<< index; 
// 2 is the wanted index because |6-6.2| is the smallest distance between the 2 vectors 
return 0;
}

确实,有一种更快的方法。只需将 v1 中的元素与 v2 中较小或相等的元素或第一个较大的元素进行比较。基本上,这个想法是有两个迭代器,ij,如果v2[j] < v1[i]则前进j,否则推进i。下面是一个可能的实现:

for (int i = 0, j = 0; i < v1.size(); i++) {
while (true) {
difference = std::abs(v1[i] - v2[j]);
if (difference < mn) {
mn = difference;
index = i;
}
// Try the next item in v1 if the current item in v2 is bigger.
if (v2[j] > v1[i])
break;
// Otherwise, try the next item in v2, unless we are at the last item.
if (j + 1 < v2.size())
j++;
else
break;
}
}

虽然它看起来仍然像一个双循环,但它最多只计算v1.size() + v2.size()次的差异,而不是v1.size() * v2.size()次。