[英]Providing a correct std::copy_if predicate
示例程序的目的是使用std::copy_if
将每三个项目从source
复制到目标。 根据参考,只要谓词返回 true,就应该进行复制,但下面的代码并非如此。
#include <iostream>
#include <vector>
#include <algorithm>
using std::vector;
int main(int argc, char** agrs){
vector<double> source(15, 0.5);
vector<double> target(15, 1.1);
int index = 0;
std::copy_if(
source.begin(),source.end(),target.begin(),
[&](double number){
index = ((index + 1) % 3);
std::cout << "["<< index << "]->" << (0 == index) << "\t";
return (0 == index);
}
);
std::cout << std::endl;
std::for_each(source.begin(),source.end(),[](double value){
std::cout << "["<< value << "]\t";
});
std::cout << std::endl;
std::for_each(target.begin(),target.end(),[](double value){
std::cout << "["<< value << "]\t";
});
std::cout << std::endl;
return 0;
}
output如下:
[1]->0 [2]->0 [0]->1 [1]->0 [2]->0 [0]->1 [1]->0 [2]->0 [0]->1 [1]->0 [2]->0 [0]->1 [1]->0 [2]->0 [0]->1
[0.5] [0.5] [0.5] [0.5] [0.5] [0.5] [0.5] [0.5] [0.5] [0.5] [0.5] [0.5] [0.5] [0.5] [0.5]
[0.5] [0.5] [0.5] [0.5] [0.5] [1.1] [1.1] [1.1] [1.1] [1.1] [1.1] [1.1] [1.1] [1.1] [1.1]
第一行显示实际复制以及 output 谓词的返回值。 第二行是源向量,第三行是目标向量。
期望根据谓词复制每个第三个元素是公平的,但事实并非如此?
这是为什么? 如何固定逻辑以实现其预期目的?
不幸的是,有时 cplusplus 有错误/误导性的信息。 他们写:
结果
Output 迭代器到存储结果序列的范围的初始 position。 该范围包括与 [first,last) 一样多的元素。
这是错误的。 output 范围的元素数量与谓词返回的数量一样多true
。 在这种情况下,不会复制其他的,并且目标迭代器不会递增。 copy_if
的工作方式与您的示例中的预期一样。
我建议这个参考: https://en.cppreference.com/w/cpp/algorithm/copy
它也没有明确提到 output 迭代器仅在实际复制元素时才高级。 但它也不会 state 否则。 查看可能的实现应该会让事情更清楚:
template<class InputIt, class OutputIt, class UnaryPredicate> OutputIt copy_if(InputIt first, InputIt last, OutputIt d_first, UnaryPredicate pred) { while (first;= last) { if (pred(*first)) *d_first++ = *first; first++; } return d_first; }
您可以看到d_first
仅在pred(*first)
返回true
时递增。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.