gpt4 book ai didi

c++ - 为什么我们需要 remove_copy_if?

转载 作者:行者123 更新时间:2023-11-30 01:41:10 25 4
gpt4 key购买 nike

根据http://www.cplusplus.com中的代码

template <class InputIterator, class OutputIterator, class UnaryPredicate>
OutputIterator remove_copy_if (InputIterator first, InputIterator last,
OutputIterator result, UnaryPredicate pred)
{
while (first!=last) {
if (!pred(*first)) {
*result = *first;
++result;
}
++first;
}
return result;
}

template <class InputIterator, class OutputIterator, class UnaryPredicate>
OutputIterator copy_if (InputIterator first, InputIterator last,
OutputIterator result, UnaryPredicate pred)
{
while (first!=last) {
if (pred(*first)) {
*result = *first;
++result;
}
++first;
}
return result;
}

唯一的区别是

 if (!pred(*first)) //copy if is if (pred(*first)) {

remove_copy_if 可以使用模拟

copy_if(it1, it2, not1(pred));

那么为什么我们需要 remove_copy_if?

最佳答案

为了了解历史,最好的问题是,为什么我们需要 copy_if

如果你看,remove_copy_if之前是 , 而 copy_if 中首次亮相.

你是对的,仿函数结果的反转是将这两者分开的全部,但正数更容易理解,因此引入了 copy_if。引用自JaggedSpire's link :

This is a frequently requested addition, mentioned in (for example) the latest edition of The C++ Programming Language. It is formally redundant, since it's just the inverse of remove_copy_if: copying all elements that satisfy a predicate p is just the same as not copying all elements that satisfy !p. It's worth adding anyway. First, C++ isn't really a functional language and transforming a predicate into its negation is sometimes awkward. Second, the workaround of using double negatives is not unconfusing.

关于c++ - 为什么我们需要 remove_copy_if?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41860768/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com