在C ++中初始化大型二维数组 [英] Initialize large two dimensional array in C++

查看:133
本文介绍了在C ++中初始化大型二维数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在一个类中具有 static constant 二维数组.数组相对较大,但是我只想初始化一些元素,而其他元素可能是编译器将其初始化为的任何元素.

I want to have static and constant two dimensional array inside a class. The array is relatively large, but I only want to initialize a few elements and others may be whatever compiler initializes them to.

例如,如果一个类的定义如下:

For example, if a class is defined like:

class A {
public:
  static int const test[10][10];
};

int const A::test[10][10] = {
  {0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, 
  {0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  {0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  {0, 0, 0, 7, 7, 7, 7, 0, 0, 0},
  {0, 0, 0, 7, 7, 7, 7, 0, 0, 0},
  {0, 0, 0, 7, 7, 7, 7, 0, 0, 0},
  {0, 0, 0, 7, 7, 7, 7, 0, 0, 0},
  {0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  {0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  {0, 0, 0, 0, 0, 0, 0, 0, 0, 0}
};

我只想对标记为'7'的元素进行初始化,如何在相同的元素上执行此操作,但是要使用更大的数组,例如array [1024] [1024]?

and I am interested only to initialize the elements marked with '7', how do I do this on the same elements, but with array of larger size, like array[1024][1024]?

推荐答案

已初始化的数组的任何部分(超出初始化范围的部分)都将初始化为0.因此:

Any part of an array which is initialized, that is beyond the initialization, is initialized to 0. Hence:

int const A::test[10][10];           // uninitialized

int const A::test[10][10] = { {0} }; // all elements initialized to 0.

int const A::test[10][10] = {1,2};   // test[0][0] ==1, test[0][1]==2, rest==0

这意味着您只需初始化最后一个非零值即可:

That means all you have to initialize is up to the last non-zero:

int const A::test[10][10] = { 
  {0, 0, 0, 0, 0, 0, 0, 0, 0, 0},  
  {0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, 
  {0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, 
  {0, 0, 0, 7, 7, 7, 7, 0, 0, 0}, 
  {0, 0, 0, 7, 7, 7, 7, 0, 0, 0}, 
  {0, 0, 0, 7, 7, 7, 7, 0, 0, 0}, 
  {0, 0, 0, 7, 7, 7, 7, 0, 0, 0}
};

这不是最佳解决方案,但可以节省一些工作.

It is not the best solution, but will save some work.

这篇关于在C ++中初始化大型二维数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆