我们可以通过流行的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()
。 - 第三, using
std::remove_if
不适用于关联容器。
在c++17的范围内,我们是否有任何通用且不易出错的std::erase-std::remove_if
东西,或者在c++20中是否会有这样的实用程序?std::erase_if