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 ax = 0; ax < a_size; ax += 2)
Just be careful if a_size
is close to INT_MAX
.
A loop should be good enough. As Pete pointed out, you can avoid the modulo test.
for (int ax = 0; ax < a_size; ax += 2)
...
C++ offers support for slicing via the valarray header (e.g., take a look at std::slice_array).
I don't know if that is what you are looking for. It is intended for heavyweight numeric computations. If you are unsure, I think the simple loop is the right answer.
If by efficient, you mean faster with a smaller memory footprint, then I would opt to use pointers instead of array access. For example, what you want can be implemented in the following way with pointers.
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* a_ptr = a;
int* a_end_ptr = a_ptr + a_size;
int* b_ptr = b;
while(a_ptr < a_end_ptr) {
*b_ptr = *a_ptr;
b_ptr++;
a_ptr += 2;
}
}
This example should be slightly faster than the array access examples and I encourage you to time it and see for yourself. However one thing you should always be aware of when making these optimizations is to look at whether it matters in the large scheme of the program (don't spend time when you don't have to).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With