c++ - Copy every other element using standard algorithms (downsampling) -


say have std::vector n elements. copy every n-th element of new vector, or average element copy (downsample original vector). want this

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

or

for(long = 0; < 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); } 

is there way using standard algorithms of c++? using std::copy binary functions? have billions of elements want treat way, , want fast possible.

ps: prefer not use external libraries such boost.

for readability, loop idea, pointed out vlad in comments. if want someting this, 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; } );  

if want average, it's getting worse you'd have similar tricks combining transform() copy_if().

edit: if you're looking performance, you'd better stick loop, stressed in comments davidhigh: avoid overhead of call lambda function each element.

if you're looking algorithm because you're doing often, you'd better write own generic one.


Comments

Popular posts from this blog

facebook - android ACTION_SEND to share with specific application only -

python - Creating a new virtualenv gives a permissions error -

javascript - cocos2d-js draw circle not instantly -