在C ++中使用条件擦除循环 [英] Erase in a loop with a condition in C++

查看:61
本文介绍了在C ++中使用条件擦除循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有更好的书写方式:

Is there a better way to write:

for (auto i = container.begin(); i != container.end();)
{
    if (condition(i))
    {
       i = container.erase(i);
       continue;
    }
    ++i;
}

这段代码可以满足我的要求,但是感觉很糟糕.

This code does what I want, but it feels like bad style.

我该如何改善?

我的容器是 std :: map ,但是通用的解决方案会很酷.

My container is std::map, but a generic solution would be cool.

推荐答案

使用擦除 + remove_if :

auto pred = /* lambda or something*/
container.erase(std::remove_if(container.begin(),
                               container.end(),
                               pred)

这篇关于在C ++中使用条件擦除循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆