简体   繁体   English

C ++初始化类的成员数组的所有值

[英]C++ initialize all values of a member array for a class

In C++ how initialize all values of a member array for a class? 在C ++中如何初始化类的成员数组的所有值?

#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

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) (这些beginend函数可以在C ++ 11中的命名空间std中找到,或者您可以在C ++ 03中自己轻松实现它们

This was a glaring shortcoming of C++03. 这是C ++ 03的一个明显缺点。 In C++11 this has been fixed, and you can now initialize everything, including arrays: 在C ++ 11中,这已得到修复,您现在可以初始化所有内容,包括数组:

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++.) (在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); 在C ++ 03中,您根本无法初始化数组成员,但您可以在构造函数体中将设置为有意义的内容,例如通过std::fill(n, n + MAX_MATRIX, 0); .

(Of course it would be a lot nicer to say std::array<int, MAX_MATRIX> n; .) (当然,说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. 数组n_init被初始化一次并存储在内存中,然后所有后续构造都是一个没有循环的快速内存副本。 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. 如果增加MAX_MATRIX的大小, MAX_MATRIX像循环索引那样增加速度,特别是如果你多次调用Matrix::Matrix()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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