我试图根据特定条件从地图中删除一系列元素。我如何使用 STL 算法来做到这一点?
最初我想使用remove_if
但这是不可能的,因为 remove_if 不适用于关联容器。
是否有任何适用于 map 的“remove_if”等效算法?
作为一个简单的选择,我想循环遍历地图并擦除。但是循环遍历地图并擦除安全选项吗?(因为迭代器在擦除后变得无效)
我使用了以下示例:
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;
}