在C++中查找两个向量之间最相似的值
find the most similar value between two vectors in C++
我有两个排序向量,我想找到 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 中较小或相等的元素或第一个较大的元素进行比较。基本上,这个想法是有两个迭代器,i
和j
,如果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()
次。
相关文章:
- 将向量之间的数字放在另一个向量之间<vector>>如果两个数字的差值为 1
- 在C++中查找两个向量之间最相似的值
- C++在 2 个向量向量之间交换向量
- p_threads初始化中向量和数组之间的区别
- 查找多个向量之间的公共元素(无整数元素)
- 在两个类实例之间共享向量
- C++向量:clear() 和 resize() 之间的区别
- 由 std::shared_ptr 向量指向的数据之间的线程同步
- C++ std::vector 创建对象然后添加对象与在向量中创建对象之间的区别?
- C 计算两个3D向量之间的角度(0至360)
- 在C 中,是否有可能在不兼容类型的std ::向量对象之间传输不同类型的缓冲区
- C++:快速/并行计算两个"std::vector<double>"向量之间的L1距离
- 计算三个或更多向量之间的向量
- 如何在C++中找到两个向量之间的最小(优化)距离
- 列表和向量的索引之间的差异
- 如何在指定数据之间将数据从一个向量获取到另一个向量
- 编译器如何在向量vs Initializer_list之间做出决定
- 字符串和向量<string>元素之间的区别
- 在两个std::向量之间匹配元素
- 用整数密钥和向量的地图之间的差异