地图 - 找到最近的价值? [英] Map - finding nearest value?

查看:163
本文介绍了地图 - 找到最近的价值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试在 QMap 中找到最近的RGB值(我知道它可能应该是HSV,但这不是问题)。这是我到目前为止:

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

我的地图看起来像这样有索引:

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



当我的 current_rgb 是例如 4285046165 它是确定,但如果有一些值大于最大索引,程序崩溃。

可能因为 .value()尝试取消引用不存在的项?



这看起来像是您自己的自定义地图实现(或包装器),但您的逻辑似乎不正确


  1. 每次都调用 lowerBound - 除非您要查找的项目是地图

  2. 如果是地图中的第一个,您再次进行搜索???

  3. 如果不是您重新搜索发现重复操作),如果没有找到,查找最近(这是好的),但是你处理的情况下,没有(即在 lowerBound ) ?

逻辑应该是:

  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
}
//现在你知道你有一个有效的迭代器 - de-reference
mi = * it.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?

解决方案

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

这篇关于地图 - 找到最近的价值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆