Reputation: 261
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?
}
Upvotes: 3
Views: 8173
Reputation: 477100
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, e.g. via std::fill(n, n + MAX_MATRIX, 0);
.
(Of course it would be a lot nicer to say std::array<int, MAX_MATRIX> n;
.)
Upvotes: 4
Reputation: 1341
#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.
Upvotes: 0
Reputation: 104698
There's a type for this:
class Matrix {
public:
Matrix() : n() { n.fill(-1); }
protected:
std::array<int, 20> n;
};
Upvotes: 2
Reputation: 234504
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)
Upvotes: 6