为什么没有 std::copy_if 算法?
C++ 中没有 std::copy_if 算法有什么具体原因吗?我知道我可以使用 std::remove_copy_if 来实现所需的行为。我认为它会出现在 C++0x 中,但是一个带有范围、输出迭代器和函子的简单的 copy_if 就很好了。是只是错过了还是有其他原因?
Is there any specific reason for not having std::copy_if algorithm in C++ ? I know I can use std::remove_copy_if to achieve the required behavior. I think it is coming in C++0x, but a simple copy_if which takes a range, a output iterator and a functor would have been nice. Was it just simply missed out or is there some other reason behind it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
多个 来源 表明它被意外地排除在STL之外。
然而,我不确定这是事实还是一个自我延续的神话。如果有人能指出比互联网上随机帖子的链接更可靠的来源,我将不胜感激。
Multiple sources indicate that it was left out of STL by accident.
However, I am not sure if that's a fact or a self-perpetuating myth. I'd appreciate if anyone would point out a source more credible than a link to a random post on the Internet.
编写自己的谓词非常容易:
编辑: 此版本适用于所有谓词:
It's dead easy to write your own:
Edit: This version works with all predicates:
为了完整起见,我将补充一点,对于那些无法在
boost/algorithm/cxx11/copy_if 中使用 c++11 版本(如我)的人,boost 有
将使用boost::algorithm::copy_if
.hppstd::copy_if
< /a> 时:示例:
输出:
Just for completeness I will add that boost has
boost::algorithm::copy_if
for those of you who cannot use c++11's version (like me) inboost/algorithm/cxx11/copy_if.hpp
which will usestd::copy_if
when:Example:
Output:
根据 Stroustrup 的《C++ 编程语言》,这只是一个疏忽。
(作为引用,在 boost 邮件列表中回答了同样的问题: copy_if< /a>)
According to Stroustrup's "The C++ Programming Language" it was just an over-sight.
(as a citation, the same question answered in boost mail-lists: copy_if)
斯特鲁斯特鲁普说他们忘记了。它是用 C++11 编写的。
但是,您可以使用
remove_copy_if
(实际上应该称为copy_if_not
)和not1
来代替。Stroustrup says they forgot it. It's in C++11.
However, you can use
remove_copy_if
(which really should be calledcopy_if_not
) along withnot1
instead.为了完整起见,如果有人用谷歌搜索这个问题,应该提到现在(C++11 之后)有一个 复制 if 算法。它的行为符合预期(将某个范围内的某些谓词返回 true 的元素复制到另一个范围)。
一个典型的用例是
Just for completeness, in case someone googles his/her way to this question, it should be mentioned that now (post C++11) there is a copy if algorithm. It behaves as expected (copies the elements in a range, for which some predicate returns true, to another range).
A typical use case would be