cannot dereference value-initialized map/set iterator C++ map中删除元素
C++ map 删除元素
C++中map删除元素,方式不对就会引起cannot dereference value-initialized map/set iterator的bug
删除map所有元素的错误代码
std::map<int, std::string> mapPerson;
mapPerson.insert(pair<int, string>(1, "Jim"));
mapPerson.insert(pair<int, string>(2, "Kim"));
mapPerson.insert(pair<int, string>(3, "LaoWang"));
for (auto i = mapPerson.begin();i != mapPerson.end();i++)
{
mapPerson.erase(i->first);
}
这样的代码必然会引起崩溃,因为一旦删除了,再进行i++操作就会崩溃
删除map所有元素的正确代码
mapPerson.erase(mapPerson.begin(), mapPerson.end());
mapPerson.clear();
方法二释放内存版
for (auto it = mapPerson.begin(); it != mapPerson.end();)
{
delete it->second;
it->second = nullptr;
it++;
}
mapPerson.clear();
for (auto it = mapPerson.begin(); it != mapPerson.end();)
{
mapPerson.erase(it++);
}
删除map中指定元素的错误代码
std::map<int, std::string> mapPerson;
mapPerson.insert(pair<int, string>(1, "Jim"));
mapPerson.insert(pair<int, string>(2, "Kim"));
mapPerson.insert(pair<int, string>(3, "LaoWang"));
for (auto it = mapPerson.begin(); it != mapPerson.end();it++)
{
if (it->first == 2)
{
mapPerson.erase(it);
}
}
删除map中指定元素的正确代码
C++11之后这两种写法都没问题
for (auto it = mapPerson.begin(); it != mapPerson.end();it++)
{
if (it->first == 2)
{
it=mapPerson.erase(it);
}
}
或者这样写也行:
for (auto it = mapPerson.begin(); it != mapPerson.end();)
{
if (it->first == 2)
{
it=mapPerson.erase(it);
}
else
{
it++;
}
}
|