2016-11-22 43 views
2

查找最接近QVector3D我有这样的QMAP:的Qt:在QMAP

"1" (0.183,-0.232,0.747) 
"2" (1.232, 1.322,-0.123) etc. 

我需要一个函数,其输入是QVector3D和输出最接近 键将输入向量。

例如:

InputVector(0.189,-0.234,0.755) -> Output: "1" 

任何想法如何解决这个问题?

回答

0

只是通过地图迭代和检查的距离:

int getClosestKey(const QVector3D & ref, const QMap<int, QVector3D> & map) 
{ 
    int closestKey = -1; 
    double minDistance = std::numeric_limits<double>::max(); 
    for (auto itr = map.constBegin(); itr != map.constEnd(); ++itr) 
    { 
     double d = ref.distanceToPoint(itr.value()); 
     if (d > minDistance) 
     continue; 

     closestKey = itr.key(); 
     minDistance = d; 
    } 

    return closestKey; 
}