简体   繁体   中英

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

itr is passed to erasee by value. Consequently reassigning it has no effect after erasee returns.

As a quick fix you can pass it by reference:

void erasee(std::map<int32_t, int32_t>::iterator & itr) {

Though returning a new iterator might be a more readable solution.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM