使用标准算法复制所有其他元素(降采样) [英] Copy every other element using standard algorithms (downsampling)

查看:87
本文介绍了使用标准算法复制所有其他元素(降采样)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有一个带有N个元素的 std :: vector 。我想将它的每个第n个元素复制到一个新向量,或者平均到那个元素再复制它(对原始向量进行降采样)。所以我想这样做

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 original vector). So I want to do this

std::vector<double> vec(N);
long n = 4;
std::vector<double> ds(N/n);
for(long i = 0; i < ds.size(); i+=n)
{
    ds[i] = vec[i*n];
}

for(long i = 0; i < ds.size(); i+=n)
{
    double tmp = 0;    
    for(long j = 0; j < n; j++)
    {
        tmp += vec[i*n+j];
    }
    ds[i] = tmp/static_cast<double>(n);
}

是否可以使用C ++的标准算法来做到这一点?像使用带有二进制函数的std :: copy一样?我想以这种方式处理数十亿个元素,并且我希望它尽可能快。

Is there a way to do this using the standard algorithms of C++? Like using std::copy with binary functions? I have billions of elements that I want to treat this way, and I want this to be as fast as possible.

PS:我宁愿不使用外部库,例如

PS: I would prefer not to use external libraries such as boost.

推荐答案

出于可读性考虑,循环是个好主意,正如Vlad在评论中指出的那样。但是,如果您真的想这样做,可以尝试:

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

如果要平均,它会变得越来越糟,因为您必须组合 transform() copy_if()

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

编辑:
如果您在寻找性能,则最好坚持循环,如评论中强调的那样由 davidhigh 编写:它将避免为每个元素调用lambda函数的开销。

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.

这篇关于使用标准算法复制所有其他元素(降采样)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆