BAD_ACCES映射 C++ 上的迭代器
BAD_ACCES iterator on map c++
我正在尝试使用这样的地图中的地图实现一个函数:
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::count
或map::iterator
杂耍.
相关文章:
- 使用std::multimap迭代器创建std::list
- 来自 std::list 的迭代器 .end() 按预期返回"0xcdcdcdcdcdcdcdcd"但 .begin()
- C++中带有List类的迭代器Segfault
- 如何在c++迭代器类型中包装std::chrono
- 集合上的输出迭代器:assign和increment迭代器
- Boost Spirit,获取迭代器内部语义动作
- 对于set上的循环-获取next元素迭代器
- 为什么output_editor Concept不需要output_e迭代器标记
- c++17文件系统::recursive_directory迭代器()在mac上没有给出这样的目录,但在windows上
- 使用迭代器时如何访问对象在向量中的位置?
- std::vector::迭代器是否可以合法地作为指针
- 跟随整数索引列表的自定义类迭代器
- 不明白迭代器,引用和指针失效,一个例子
- 我可以使用反向迭代器作为ForwardIt吗
- ESP8266单片机矢量迭代器的C++问题
- 如何在C++中将迭代器作为函数参数传递
- 是否应避免从非常量迭代器转换为常量迭代器?
- 如何在 c++ 中将字符串迭代器变量传递给函数?
- 为什么 vector 的随机访问迭代器给出与指针不同的内存地址?
- 为什么 C++ std::unordered_map 从 emplace/ 找到返回一个迭代器?