gpt4 book ai didi

c++ - map C++ 上的 BAD_ACCES 迭代器

转载 作者:行者123 更新时间:2023-11-30 03:30:51 25 4
gpt4 key购买 nike

我正尝试在这样的 map 中使用 map 实现一个功能:

typedef std::map<int, float> inner_map;
typedef std::map<int, inner_map> outer_map;

我正在用这种方式填充 map 。这个想法是第一个映射包含一个 int 键和另一个包含另一个键和一个 float 的映射。如果我获得的对是已知的,我会增加值,否则我会填充 map 。

for (int y = 2; y < imgSize.y - 2; y++){
for (int x = 2; x < imgSize.x - 2; x++) {
thisPos = x + y*imgSize.x ;

{SOME CODE}

lj = labelMap[thisPos] ;

if (condition) {
// get the 2 label
li = pro_label_mod[thisPos] ;

// look if it lj is in the map
is_lj = pi_matrix.count(lj) ;

// this lj has already been observed
if (is_lj == 1) {
is_li = pi_matrix[lj].count(li);

// this pair is known -> I increment
if (is_li==1) {
pi_matrix[lj][li] += 1.0f ;
}
else {
pi_matrix.at(lj).insert(pi_matrix[lj].end(), std::make_pair(li, 1.0f)) ;
}
}
else {
inner_map inter ; inter.insert(std::make_pair(li, 1.0f)) ;
pi_matrix.emplace(lj, inter) ;
}
}
numb_lj[lj] += 1.0f ;
}
}

然后,我想在我的代码中遍历 map 。我用迭代器做到了这一点,例如:

std::vector<std::pair<int,float> > max_pi(size_lj) ;

float maxValue, thisValue ; int label_max ;

for (outer_map::iterator it_lj = pi_matrix.begin(), it_lj_end = pi_matrix.end(); it_lj != it_lj_end; ++it_lj) {
maxValue = 0.0f ;
label_max = 0 ;

inner_map &innerMap = it_lj->second;

for(inner_map::iterator it_li = innerMap.begin(), it_li_end = innerMap.end(); it_li != it_li_end; ++it_li) {
thisValue = it_li->second / numb_lj[it_lj->first] ;

if (thisValue >= maxValue) {
maxValue = thisValue ;
label_max = it_li->first ;
}
}

max_pi[it_lj->first] = std::make_pair(label_max, maxValue) ;
i+=1;
}

但是,我在 for 循环的行(第一个或第二个)遇到段错误。但 !不是每一次。我在每一帧调用这个函数,我可以在没有 BAD_ACCESS 的情况下进行 5 次调用,突然,它崩溃了。有时在第一次调用之后,然后是第 10 次调用。

我真的不明白为什么以及如何解决它..

提前感谢您提供任何可能有帮助的线索/评论!

最佳答案

看来你设计的嵌套map正在引起各种不必要的并发症。更自然的出现一个带有pair<int,int>的单图作为关键:

using key_type = std::pair<int,int>;
using map_type = std::map<key_type,float>;

void add_to_map(map_type&map, key_type const&key)
{
map[key] += 1.f; // also works as desired if map.count(key)==0
}

// find key and value of first element with maximum value
map_type::value_type find_max(map_type const&map)
{
auto max = map.begin();
for(auto it=max; it!=map.end(); ++it)
if(it.second > max.second)
max = it;
return *max;
}

无需处理 map::countmap::iterator .

关于c++ - map C++ 上的 BAD_ACCES 迭代器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44682645/

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