Mat*_*ith 132 c++ iterator stl
在下面的代码中,我遍历一个map并测试是否需要擦除一个元素.擦除元素并继续迭代是否安全,或者我是否需要在另一个容器中收集密钥并执行第二个循环来调用erase()?
map<string, SerialdMsg::SerialFunction_t>::iterator pm_it;
for (pm_it = port_map.begin(); pm_it != port_map.end(); pm_it++)
{
if (pm_it->second == delete_this_id) {
port_map.erase(pm_it->first);
}
}
Run Code Online (Sandbox Code Playgroud)
Mar*_*ork 183
这已在C++ 11中得到修复(或擦除已在所有容器类型中得到改进/保持一致).
擦除方法现在返回下一个迭代器.
auto pm_it = port_map.begin();
while(pm_it != port_map.end())
{
if (pm_it->second == delete_this_id)
{
pm_it = port_map.erase(pm_it);
}
else
{
++pm_it;
}
}
Run Code Online (Sandbox Code Playgroud)
擦除映射中的元素不会使任何迭代器无效.
(除了被删除的元素上的迭代器)
实际插入或删除不会使任何迭代器失效:
另见这个答案:
Mark Ransom Technique
但是你需要更新你的代码:
在你的代码中,你在调用erase后递增pm_it.此时为时已晚,已经失效.
map<string, SerialdMsg::SerialFunction_t>::iterator pm_it = port_map.begin();
while(pm_it != port_map.end())
{
if (pm_it->second == delete_this_id)
{
port_map.erase(pm_it++); // Use iterator.
// Note the post increment.
// Increments the iterator but returns the
// original value for use by erase
}
else
{
++pm_it; // Can use pre-increment in this case
// To make sure you have the efficient version
}
}
Run Code Online (Sandbox Code Playgroud)
Ala*_*ker 12
这就是我这样做的方式......
typedef map<string, string> StringsMap;
typedef StringsMap::iterator StrinsMapIterator;
StringsMap m_TheMap; // Your map, fill it up with data
bool IsTheOneToDelete(string str)
{
return true; // Add your deletion criteria logic here
}
void SelectiveDelete()
{
StringsMapIter itBegin = m_TheMap.begin();
StringsMapIter itEnd = m_TheMap.end();
StringsMapIter itTemp;
while (itBegin != itEnd)
{
if (IsTheOneToDelete(itBegin->second)) // Criteria checking here
{
itTemp = itBegin; // Keep a reference to the iter
++itBegin; // Advance in the map
m_TheMap.erase(itTemp); // Erase it !!!
}
else
++itBegin; // Just move on ...
}
}
Run Code Online (Sandbox Code Playgroud)