Search code examples
c++qtqmap

Map - finding nearest value?


I am trying find nearest RGB value in QMap (I know it probably should be HSV, but that is not the problem). Here is what I got so far:

        it = images_map.find(current_rgb);

        if(it != images_map.begin()){
            mi = images_map.lowerBound(current_rgb).value();
        }
        else{
            mi = images_map.upperBound(current_rgb).value();
        }

My map looks like this has that indexes:

images_map[ 4283914078 ] 
images_map[ 4284046165 ] 
images_map[ 4284902241 ] 
images_map[ 4289239953 ] 
images_map[ 4282200377 ] 
images_map[ 4289440688 ] 

When my current_rgb is for example 4285046165 it is OK, but if there is some value greater than greatest index, program crashes. What am I doing wrong?


Solution

  • Possibly because .value() tries to de-reference a non-existing item?

    This looks like your own custom map implementation (or wrapper), but your logic appears to be incorrect

    1. You call lowerBound every time - except if the item you are looking for is the first in the map
    2. If it is the first in the map, you do a search again???
    3. If it's not you search again (which if already found is repeating the operation again), else if not found, looks for nearest (which is okay), however do you handle the case where there is none (i.e. in lowerBound)?

    The logic should be something like:

    it = images_map.find(current_rgb);
    
    if(it == images_map.end())
    {
      it = images_map.lowerBound(current_rgb);
      if (it == images_map.begin())
      {
        it = images_map.upperBound(current_rgb);
        if (it == images_map.end()) 
          // throw error
      }
      // now you know you have a valid iterator - de-reference
      mi = *it.value();
    }