2016-11-22 44 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; 
}