3

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?

SingerOfTheFall
  • 29,228
  • 8
  • 68
  • 105
Michael
  • 43
  • 3

1 Answers1

0

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;
}
Tomas
  • 2,170
  • 10
  • 14