问题描述
我正在试图从特定情况下从地图中删除一系列元素。如何使用STL算法?
I was trying to erase a range of elements from map based on particular condition. How do I do it using STL algorithms?
最初我想到使用 remove_if
,但不可能的是remove_if对于关联容器不起作用。
Initially I thought of using remove_if
but it is not possible as remove_if does not work for associative container.
有没有可用于map的remove_if等效算法?
Is there any "remove_if" equivalent algorithm which works for map ?
作为一个简单的选择,我想到循环遍历地图并清除。但是循环遍历地图并擦除一个安全的选项?(因为迭代器在擦除后无效)
As a simple option, I thought of looping through the map and erase. But is looping through the map and erasing a safe option?(as iterators get invalid after 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;
}
推荐答案
几乎。
Almost.
for(; iter != endIter; ) {
if (Some Condition) {
aMap.erase(iter++);
} else {
++iter;
}
}
你最初会增加迭代器如果你从它删除一个元素,那么两次您可以跳过需要擦除的元素。
What you had originally would increment the iterator twice if you did erase an element from it; you could potentially skip over elements that needed to be erased.
这是一个常见的算法,我在许多地方使用过并记录在案。
This is a common algorithm I've seen used and documented in many places.
您是正确的,迭代器在擦除后无效,但只有迭代器引用被擦除的元素,其他迭代器仍然有效。因此在erase()调用中使用iter ++。
You are correct that iterators are invalidated after an erase, but only iterators referencing the element that is erased, other iterators are still valid. Hence using iter++ in the erase() call.
这篇关于remove_if等价于std :: map的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!