C ++ [] or ++ array pointers

lets say that I want to iterate over an array of two pairs and sum them up. I have two ways to do this.

AND)

double sum (double * series, int size) {
    double sum = 0.0;
    for (int i = 0; i < size; i++) {
        sum += *series++;
    }
    return sum;
}

AT)

double sum (double * series, int size) {
    double sum = 0.0;
    for (int i = 0; i < size; i++) {
        sum += series[i];
    }
    return sum;
}

which is better and why / when should I use one over the other.

+5
source share
5 answers

This is a matter of readability; it should not affect performance. I think B is the most readable and therefore preferred.

I could also suggest a third option based on the range (pay attention to the parameters beginand end):

double sum (double* begin, double* end) {
    double sum = 0.;
    for (double* it = begin; it != end; ++it) {
        sum += *it;
    }
    return sum;
}

In many cases, this is idiomatic C ++ and is easier to generalize. This does not mean that it is always preferable, it is another option on the issue of readability and maintainability.

+6
source

B, :

#include <numeric>

double sum(const double* const series, const int size) {
    return std::accumulate(series, series + size, 0.0);
}
+5

, ; , . .


, , ++. , std::vector.

+4

.

1978 PDP-11, , , + .

PS The setting series -= size;does not work, because it seriesis transmitted by value.

+1
source

C ++ 11 way to iterate over an array (if you don’t just want to sum them up and what to accumulate does not meet your needs):

double sum (const double * series, int size) { 
    double sum = 0.0; 
    for_each (series, series + size, [&](double v) { 
        sum += v;
    });
    return sum; 
} 

Note that if you used a vector or list, you would get almost the same code:

double sum (const vector<double>& series) { 
    double sum = 0.0; 
    for_each (begin(series), end(series), [&](double v) { 
        sum += v;
    });
    return sum; 
} 
0
source

All Articles