简体   繁体   English

如何将值添加到多数组?

[英]c# - How can I add a value to a multi array?

I have this array here: 我在这里有这个数组:

float[, ,] vectors;

int pos = 0;

void Start() {
   vectors = new float[,,] { {
       { 0, 1, 1 }, 
       { 0, 2, 2 } }
    };        
}

This works. 这可行。 I fill the array with numbers. 我用数字填充数组。

Now I want to add some values again to a given position. 现在,我想再次向给定位置添加一些值。 But how? 但是如何?

This are not working: 这不起作用:

vectors[pos] = new float[,,] { { { 33, 44, 55 } } };     

or 要么

vectors[pos] = { { { 33, 44, 55 } } };     

I searched, but not found the right answer. 我搜索了但没有找到正确的答案。

EDIT: I want something like this: 编辑:我想要这样的事情:

[0]+
   [0] {1, 2, 3},
   [1] {4, 5, 6}

[1]+
   [0] {11, 22, 33},
   [1] {44, 55, 66},
   [2] {77, 88, 99}

...
etc.

Now, eg I want add values {10,10,10} to pos = 0. But how? 现在,例如,我想将值{10,10,10}添加到pos =0。但是如何?

If you want to add values I suggest using generic lists instead of arrays. 如果要添加值,我建议使用通用列表而不是数组。 And you should create your own Vector class or find one that is suitable to your needs like this. 并且您应该创建自己的Vector类,或者找到适合您需求的类。

public class Vector
{
    public float X { get; private set; }
    public float Y { get; private set; }
    public float Z { get; private set; }

    public Vector(float x, float y, float z)
    {
        X = x;
        Y = y;
        Z = z;
    }
}

Then you can do the following 然后您可以执行以下操作

var vectors = new List<List<Vector>>
{
    new List<Vector>{
        new Vector(0, 1, 1),
        new Vector(0, 2, 2)
    }
};

vectors[0].Add(new Vector(33,44,55));

And your vectors will contain 您的向量将包含

[0]
    [0] {0, 1, 1}
    [1] {0, 2, 2}
    [2] {33, 44, 55}

Note that if you need to add to the first dimention you have to do this. 请注意,如果需要添加到第一个尺寸,则必须执行此操作。

vectors.Add(new List<Vector>());

vectors[1].Add(new Vector(1, 2, 3));

And now you have 现在你有了

[0]
    [0] {0, 1, 1}
    [1] {0, 2, 2}
    [2] {33, 44, 55}
[1]
    [0] {1, 2, 3}

You should determine the other positions within the array, you are just specifying one. 您应该确定数组中的其他位置,只需指定一个即可。 If your problem cannot be solved within lists you can try array of arrays as follows 如果您的问题无法在列表中解决,则可以按以下方式尝试数组数组

float [][][] x = new float [n][m][];

// initialize the third dimension until m is reached
x[0] = new float {1,2,3,4,5}; // specify whatever value you want
x[1] = new float {3,2,4};
x[2] = new float [3];

// etc until m is reached
// do the same for the n dimension

This will work for you, the array is assigned, you cannot change it you must expand the array as is. 这将为您工作,分配了数组,您不能更改它,必须按原样扩展数组。

float[, ,] vectors;

int pos = 0;

vectors = new float[,,]
{
    { 
        { 0, 1, 2 }, { 0, 3, 4 }
    }
};        


vectors =  new float[,,]
    {
        {
            {vectors[0,0,0], vectors[0,0,1], vectors[0,0,2]}, { vectors[0,1,0], vectors[0,1,1], vectors[0,1,2] }, { 33,44,55}
        }
    };

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

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