Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Every n element of an array in C++

Tags:

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];  
    }   
}
like image 580
cpp Avatar asked Aug 11 '13 16:08

cpp


3 Answers

for (int ax = 0; ax < a_size; ax += 2)

Just be careful if a_size is close to INT_MAX.

like image 193
Pete Becker Avatar answered Nov 06 '22 14:11

Pete Becker


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.

like image 23
Philipp Claßen Avatar answered Nov 06 '22 14:11

Philipp Claßen


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).

like image 38
JustKash Avatar answered Nov 06 '22 13:11

JustKash