c++ - std::map 到 std::list 会导致 SIGSEGV

标签 c++ stdmap segmentation-fault stdlist

我想在将 std::map 转换为 std::list 时节省 RAM。因此我必须删除之间的每个元素。但我收到了 SIGSEGV。

template <class U>
auto ConvertFlatSegmentsMapToList(std::map<std::string /* relative_path */, U>& differences_map, std::list<U>& differences_list) -> void {
    for (auto& i:differences_map) {
        differences_list.push_back(i.second);
        // differences_map.erase(i.first);//TODO: SIGSEGV
    }
}

如何做到这一点?

最佳答案

如果你想节省内存,不要使用std::map,也不要使用std::list - 使用std::vector >;或者更好 - 不要使用单独的字符串,应用重复数据删除等。

话虽如此,并回答您的问题:从 map 中删除元素 invalidates iterators进入映射 - ranged-for 循环实际上是基于迭代器的。所以 - 你不能在循环期间删除。在循环后使用differences_map.clear()。您还应该注意,删除单个元素比清除整个 map 在时间上要昂贵得多。

如果你的内存力非常有限,以至于你无法同时拥有完整的 map 和完整的列表,那么你只是使用了错误的数据结构 - 因为,就像我说的,这两者都相当浪费。不过,如果您坚持,您可以重复将 *differences_map.begin() 插入列表中,然后从 map 中删除它(并且每次再次获取 .begin() ,迭代器失效后)。

关于c++ - std::map 到 std::list 会导致 SIGSEGV,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50698705/

相关文章:

c++ - 线程本地获取/释放同步

c - 我的 csv_loader() 函数中出现段错误

c++ - 使用 std::for_each 遍历树

c++ - gets() 不接受输入

C++:std::map 中的引用计数值; std::multimap 是更好的选择吗?

c++ - 插入 C++ std::map 时出现奇怪的错误

C++:即使被转换的对象不是 NULL,dynamic_cast 也会导致 SEGFAULT。怎么会这样?

c - 为什么 "mov %%rsp, %%rbp"导致段错误?

c++ - dynamic_cast<>有多快

c++ - 无法使用 end() 获取 map 的第二个字段