Copy every other element using standard algorithms (downsampling)

前端 未结 4 1332
长情又很酷
长情又很酷 2021-01-22 01:52

say I have a std::vector with N elements. I would like to copy every n-th element of it to a new vector, or average up to that element then copy it (downsample the

4条回答
  •  既然无缘
    2021-01-22 02:13

    For readability, the loop would be a good idea, as pointed out by Vlad in the comments. But if you really want to do someting like this, you could try:

    int cnt=0,n=3; 
    vector u(v.size()/3); 
    copy_if (v.begin(), v.end(), u.begin(), 
              [&cnt,&n] (int i)->bool {return ++cnt %n ==0; } ); 
    

    If you want to average, it's getting worse as you'd have to similar tricks combining transform() with copy_if().

    Edit: If you're looking for performance, you'd better stick to the loop, as stressed in the comments by davidhigh: it will avoid the overhead of the call to the lambda function for each element.

    If you're looking for an algorithm because you're doing this very often, you'd better write your own generic one.

提交回复
热议问题