Sunday, 11 August 2013

Every n element of an array in C++

Every n element of an array in C++

Are there more efficient methods of getting every second (every n in
general) element of an array then the simple for loop below? For example
with the use of generic algorithms?
#include<iostream>
using namespace std;
int main()
{
const int a_size = 6, b_size = 3;
int a[a_size] = {1, 3, 6, 3, 2, 7};
int b[b_size];
int bx = 0;
for ( int ax = 0; ax < a_size; ++ax )
{
if (ax % 2 == 0)
b[bx++] = a[ax];
}
for ( int bx = 0; bx < b_size; ++bx )
cout << b[bx] << ' ';
cout << endl;
}

No comments:

Post a Comment