与std :: map等效的remove_if

我试图根据特定条件从地图中删除一系列元素。我该如何使用STL算法?


最初,我想到使用,remove_if但是由于remove_if对于关联容器不起作用,因此无法使用。


是否有适用于地图的“ 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;

}


守候你守候我
浏览 1341回答 3
3回答

12345678_0001

几乎。for(; iter != endIter; ) {&nbsp; &nbsp; &nbsp;if (Some Condition) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; aMap.erase(iter++);&nbsp; &nbsp; &nbsp;} else {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ++iter;&nbsp; &nbsp; &nbsp;}}如果您确实从迭代器中删除了一个元素,则原来将其增加两次。您可能会跳过需要删除的元素。这是我在许多地方见过使用和记录的常见算法。正确的是,擦除后迭代器无效,但是仅迭代器引用了要擦除的元素,其他迭代器仍然有效。因此iter++在erase()通话中使用。
打开App,查看更多内容
随时随地看视频慕课网APP