【问题标题】:Does C++ standard library provide more compact and generalized version of the erase–remove idiom?C++ 标准库是否提供更紧凑和更通用的擦除删除习惯用法?
【发布时间】:2019-11-13 12:23:01
【问题描述】:

我们可以通过流行的erase–remove idiom 从容器中删除一个元素/条目。 但是,我们中的许多人在应用这个成语时会遇到一些问题:

  • 一个人很容易陷入错别字之类的陷阱

    c.erase(std::remove_if(c.begin(), c.end(), pred));
    //                                             , c.end() //---> missing here
    

    或

    c.erase((std::remove_if(c.begin(), c.end(), pred), c.end()))
    //      ^^                                               ^^
    // extra () makes it pass only c.end() to the c.erase
    
  • 它甚至遵循错误语义的容器,如 std::list 通过不选择自己的成员 std::list::remove_if() 为成语。
  • 第三,使用std::remove_ifdoes not work for associative containers。

在 的范围内,我们有没有比std::erase-std::remove_if 或类似std::erase_if 的东西更通用且不易出错的东西,或者 中是否会有这样的实用程序?

【问题讨论】:

    标签: c++17 c++20 c++ c++17 c++-standard-library c++20 erase-remove-idiom


    【解决方案1】:

    不在的范围内,而是以后!

    是的。在n4009 paper 中提到了一致性容器擦除的提议,并最终在C++20 standard as std::erase_if 中采用,这是每个容器的非成员函数。

    这确保了 std::basic_string 和 all standard containers 的统一容器擦除语义,std::array 除外(因为它具有固定大小)。

    这意味着样板代码

    container.erase(
        std::remove_if(
            container.begin(), container.end(),
            [](const auto& element) ->bool { return /* condition */; }),
        vec.end());
    

    将简单地融合为

    的概括形式
    std::erase_if(container, [](const auto& element) ->bool { return /* condition */; });
    

    其次,这种统一的语法为每个容器选择正确的语义。这意味着


    除此之外,标准还添加了std::erase用于序列容器的形式

    std::erase(container, value_to_be_removed);
    

    【讨论】:

    • 如何为我自己的容器扩展它?我自己的erase_if(...) 会被 ADL 找到吗?
    • @Justin 如果我理解正确,为自己的容器定义一个非成员 erase_if(...) 还不够吗?也许将std:: 的范围添加到命名空间std。但后面的部分我不确定。
    • 确实,从论文来看,这个实用程序是为每个标准容器指定的,并且不使用 ADL。由于不允许将自定义重载添加到 std,因此为您自己的容器自定义重载的方法是在您自己的命名空间中定义您自己单独的 erase_if,它可以转发到 std::erase_if 或您自己的容器' .
    • @Justin No ADL 意味着像{ using std::erase_if; erase_if(...); } 这样不合格的电话不会帮助找到自己的非会员erase_if,对吧?
    • @TedLyngmo 你可以这样写,它会找到你自己的erase_if(前提是它可以被 ADL 找到,比如它与你的容器定义在同一个命名空间中)。跨度>
    猜你喜欢
    • 1970-01-01
    • 2011-04-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多