gpt4 book ai didi

c++ - map - 找到最近的值?

转载 作者:行者123 更新时间:2023-11-30 02:08:29 24 4
gpt4 key购买 nike

我正在尝试在 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();
}

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

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

例如,当我的 current_rgb4285046165 时,它没问题,但如果某个值大于最大索引,程序就会崩溃。我做错了什么?

最佳答案

可能是因为 .value() 试图取消引用一个不存在的项目?

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

  1. 你每次都调用 lowerBound - 除非你正在寻找的项目是 map 中的第一个
  2. 如果它是 map 中的第一个,你再做一次搜索???
  3. 如果不是你再次搜索(如果已经找到则再次重复操作),否则如果没有找到,寻找最近的(这没关系),但是你是否处理没有的情况(即在 下限)?

逻辑应该是这样的:

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

关于c++ - map - 找到最近的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6730136/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com