Clean ways to write multiple 'for' loops

前端 未结 16 973
傲寒
傲寒 2020-12-22 15:22

For an array with multiple dimensions, we usually need to write a for loop for each of its dimensions. For example:

vector< vector< vector         


        
16条回答
  •  抹茶落季
    2020-12-22 15:47

    I caveat this answer with the following statement: this would only work if you were operating on an actual array - it wouldn't work for your example using std::vector.

    If you are performing the same operation on every element of a multi-dimensional array, without caring about the position of each item, then you can take advantage of the fact that arrays are placed in contiguous memory locations, and treat the whole thing as one big one-dimensional array. For example, if we wanted to multiply every element by 2.0 in your second example:

    double B[3][3][3];
    // ... set the values somehow
    double* begin = &B[0][0][0];     // get a pointer to the first element
    double* const end = &B[3][0][0]; // get a (const) pointer past the last element
    for (; end > begin; ++begin) {
        (*begin) *= 2.0;
    }
    

    Note that using the above approach also allows the use of some "proper" C++ techniques:

    double do_something(double d) {
        return d * 2.0;
    }
    
    ...
    
    double B[3][3][3];
    // ... set the values somehow
    double* begin = &B[0][0][0];  // get a pointer to the first element
    double* end = &B[3][0][0];    // get a pointer past the last element
    
    std::transform(begin, end, begin, do_something);
    

    I don't generally advise this approach (preferring something like Jefffrey's answer), as it relies on having defined sizes for your arrays, but in some cases it can be useful.

提交回复
热议问题