简体   繁体   中英

Qt: Find closest QVector3D in QMap

i have a QMap like this:

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

I need a function which input is a QVector3D and which output is the closest key to the input vector.

For Example:

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

Any ideas how to solve this problem?

just iterate through the map and check the distances:

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM