jeudi 31 décembre 2020

erase map element using an iterator inside a function

I need to erase map elements using an iterator inside a function which takes map iterator as argument, but getting runtime error(free(): double free detected). This is my code:

#include <iostream>
#include <map>

std::map<int32_t, int32_t> mapp;

void erasee(std::map<int32_t, int32_t>::iterator itr) {
    itr = mapp.erase(itr);
}

int main()
{
    mapp.emplace(1, 1000);
    
    std::map<int32_t, int32_t>::iterator itr = mapp.begin();
    while(itr != mapp.end()) {
        std::cout << "before" << std::endl;
        
        erasee(itr);
        
        std::cout << "after" << std::endl;
    }
    
    return 0;
}

Aucun commentaire:

Enregistrer un commentaire