Erase/Remove contents from the map (or any other STL container) while iterating it

前端 未结 9 1350
无人及你
无人及你 2020-12-01 07:55

Allegedly you cannot just erase/remove an element in a container while iterating as iterator becomes invalid. What are the (safe) ways to remove the elements that meet a cer

9条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-01 08:45

    1.For std::vector<> :

    std::vector  vec;
    vec.erase(std::remove(vec.begin(),vec.end(), elem_to_remove), vec.end());
    

    2.For std::map<> always use std::map::erase()

    std::map myMap;
    myMap.emplace(std::make_pair(1, "Hello"));
    myMap.emplace(std::make_pair(2, "Hi"));
    myMap.emplace(std::make_pair(3, "How"));
    myMap.erase( 1);//Erase with key
    myMap.erase(myMap.begin(), ++myMap.begin() );//Erase with range
    for( auto &ele: myMap)
    {
        if(ele.first ==1)
        {
            myMap.erase(ele.first);//erase by key 
            break; //You can't use ele again properly 
                   //wthin this iteration, so break.
        }
    }
    
    1. For std::list use std::list::erase()

提交回复
热议问题