简体   繁体   中英

C++ array pointers [] or ++

lets say I want to iterate through an array of doubles and sum them. I have two ways to do this.

A)

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

B)

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.

This is a question of readability, it should not affect performance. I think B is the most readable, and therefore preferable.

I could also propose a third variant, which is range-based (note the begin and end parameters):

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

This is idiomatic C++ in many cases and generalizes more easily. That is not to say that it is always preferable, it is just another variant in a question about readability and maintainability.

I would chose style B as well, but then you should prefer standard algorithms over explicit loops:

#include <numeric>

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

Neither is inherently better than the other; you should choose whichever makes the intention of your code clearest. With any modern compiler, they should be optimised to identical machine code.


Note, however, that passing around raw pointers to raw arrays is considered bad style in C++. Consider using a container class such as std::vector .

In terms of performance there should be no difference when you use modern optimizing compiles.

Back in 1978, the first way was somewhat faster on PDP-11, because indirect autoincrement addressing required fewer cycles to process, and there was no optimizers capable of converting index+offset to autoincrement.

PS Setting series -= size; has no effect, because series is passed by value.

The C++11 way to iterate the array (if you don't want to just sum them and that accumulate doesn't fit your need) is:

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 a list you'd get pretty much 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; 
} 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM