简体   繁体   中英

C++ initialize all values of a member array for a class

In C++ how initialize all values of a member array for a class?

#define MAX_MATRIX 20
Class Matrix {
public:   
         Matrix(); //constructor
protected:
         int n[MAX_MATRIX];   // note cannot do = { 0} or w/e here
};

Matrix::Matrix()
{
     // how to set all n to -1?
}

You can use std::fill :

std::fill(begin(n), end(n), -1);

(These begin and end functions can be found in namespace std in C++11, or you can easily implement them yourself in C++03)

This was a glaring shortcoming of C++03. In C++11 this has been fixed, and you can now initialize everything, including arrays:

class Matrix
{
public:   
     Matrix() : n { } { }
protected:
     static const unsigned int MAX_MATRIX = 20;
     int n[MAX_MATRIX];
};

(The nasty preprocessor macro is also not needed in C++.)

In C++03, you simply cannot initialize an array member, but you can set it to something meaningful in the constructor body, eg via std::fill(n, n + MAX_MATRIX, 0); .

(Of course it would be a lot nicer to say std::array<int, MAX_MATRIX> n; .)

There's a type for this:

class Matrix {
public:
    Matrix() : n() { n.fill(-1); }
protected:
    std::array<int, 20> n;
};
for (unsigned i = 0; i < MAX_MATRIX; ++i) n[i] = -1;
#include <cstring>

...

Matrix::Matrix()
{
 static bool init=false;
 static int n_init[MAX_MATRIX];
 if (!init){
   for(int i=0; i<MAX_MATRIX; i++){
    n_init[i] = -1;
   }
  init = true;
 }
 memcpy(n,n_init,MAX_MATRIX*sizeof(int));
}

The array n_init is initialized exactly once and stored in memory, then all subsequent constructions are a quick memory copy with no loops. You should not see much decrease in speed if you increase the size of MAX_MATRIX as you would when looping through the index, particularly if you are calling Matrix::Matrix() many times.

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