我想根据特定条件从 map 中删除一定范围的元素,如何使用 STL 算法实现?
最初我考虑使用 remove_if
,但是它不适用于关联容器。
有没有类似于 "remove_if" 的算法可以在 map 中使用?
作为一个简单的选择,我考虑循环遍历 map 并进行删除。但是循环遍历并删除是否安全?(因为迭代器在 erase 后会变为无效)
我使用了以下示例:
bool predicate(const std::pair<int,std::string>& x)
{
return x.first > 2;
}
int main(void)
{
std::map<int, std::string> aMap;
aMap[2] = "two";
aMap[3] = "three";
aMap[4] = "four";
aMap[5] = "five";
aMap[6] = "six";
// does not work, an error
// std::remove_if(aMap.begin(), aMap.end(), predicate);
std::map<int, std::string>::iterator iter = aMap.begin();
std::map<int, std::string>::iterator endIter = aMap.end();
for(; iter != endIter; ++iter)
{
if(Some Condition)
{
// is it safe ?
aMap.erase(iter++);
}
}
return 0;
}
for(auto iter=aMap.begin(); iter!=aMap.end(); ){ ....}
来减少混乱。其他部分与其他人所说的相同。这个问题刚刚让我省了些头发分叉;-) - Atul Kumarstd::map
引入了std::erase_if
,但愿我能把我的代码带到未来。 - wcochran