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; } );
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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…