Search code examples
c++stdmapsegmentation-faultstdlist

std::map to std::list leads to SIGSEGV


I want to save RAM while converting a std::map to a std::list. Therefore I have to delete every element in between. But I get a 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
    }
}

How to do that?


Solution

  • As yussuf commented, you can find the solution at https://stackoverflow.com/a/8234813/1142788. I have adapted this to my example. (needs c++11 support)

    template <class U>
    auto ConvertFlatSegmentsMapToList(std::map<std::string /* relative_path */, U>& differences_map, std::list<U>& differences_list) -> void {
        std::clog << "differences_map: " << differences_map.size() << std::endl;    // e.g. 6
        std::clog << "differences_list: " << differences_list.size() << std::endl;  // e.g. 0
    
        for (auto i = differences_map.cbegin(); i != differences_map.cend(); i = differences_map.erase(i)) {
            differences_list.push_back(i->second);
        }
    
        std::clog << "differences_map: " << differences_map.size() << std::endl;    // e.g. 0
        std::clog << "differences_list: " << differences_list.size() << std::endl;  // e.g. 6
    }