Copy every other element using standard algorithms (downsampling)

前端 未结 4 1306
长情又很酷
长情又很酷 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:36

    You could write your own generic algorithms inspired from the design principles used in .

    For the copy of every n elements:

    template
    out_it copy_every_n( in_it b, in_it e, out_it r, size_t n) {
        for (size_t i=distance(b,e)/n; i--; advance (b,n)) 
            *r++ = *b;
        return r;
    }
    

    Example of use:

    vector v {1,2,3,4,5,6,7,8,9,10};
    vector z(v.size()/3); 
    copy_every_n(v.begin(), v.end(), z.begin(), 3);     
    

    For averaging the elements n by n, you can use:

    template
    out_it average_every_n( in_it b, in_it e, out_it r, size_t n) {
        typename out_it::value_type tmp=0;
        for (size_t cnt=0; b!=e; b++)  {
            tmp+=*b;
            if (++cnt==n) {
                cnt=0; 
                *r++=tmp/n;
                tmp=0;
            }
        }
        return r;
    }
    

    Example of use:

    vector w(v.size()/3); 
    average_every_n(v.begin(), v.end(), w.begin(), 3);  
    

    The advantage over your inital loops, is that this will work not only on vectors, but on any container providing the begin() and end() iterator. And it avoids overheads that I pointed out in my other answer.

提交回复
热议问题