BAD_ACCES映射 C++ 上的迭代器

BAD_ACCES iterator on map c++

本文关键字:迭代器 C++ 映射 ACCES BAD      更新时间:2023-10-16

我正在尝试使用这样的地图中的地图实现一个函数:

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

我以这种方式填充地图。这个想法是第一个映射包含一个 int 键,另一个映射包含另一个键和一个浮点数。如果我获得的对是已知的,我递增该值,否则我填充地图。

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

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

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杂耍.