代码之家  ›  专栏  ›  技术社区  ›  Razzupaltuff

转换结构的W/O吨新呼叫的C++数组?

  •  2
  • Razzupaltuff  · 技术社区  · 15 年前

    typedef struct someStruct {
       int val1, val2;
       double val3;
    } someStruct;
    
    someStruct a [1000] = { {0, 0, 0.0}, {1, 1, 1.0}, ... };
    

    在C中初始化这样一个表的唯一方法是

    class SomeStruct 
    {
       int val1, val2;
       double val3;
    
       public SomeStruct (int val1, int val2, double val3)
       {
          this.val1 = val1;
          this.val2 = val2;
          this.val3 = val3;
       }
    }
    
    SomeStruct[] a = new SomeStruct [1000] 
    { 
       new SomeStruct (0, 0, 0.0), 
       new SomeStruct (1, 1, 1.0), 
       ... 
    };
    

    有没有办法让一个数组成为一个类型为class SomeClass的值数组,而不是指向这些值的指针?

    我试过类似的方法

    struct SomeStruct {
       int a, b;
       double c;
       }
    
    SomeStruct[] a = new SomeStruct [1000] { {0,0,0.0}, {1,1,1.0}, ... };
    

    struct SomeStruct {
       int a, b;
       double c;
       SomeStruct (int a, int b, double c) {
          this.a = a; this.b = b; this.c = c;
          }
       }
    
    SomeStruct[] a = new SomeStruct [1000] { 
       new SomeStruct {0,0,0.0}, 
       new SomeStruct {1,1,1.0}, 
       ... 
       };
    
    3 回复  |  直到 12 年前
        1
  •  2
  •   Puppy    15 年前

    您可以在C#中使用struct关键字。C结构是值类型-结构数组是连续存储的结构,与C++标准数组相同。

        2
  •  0
  •   leppie    15 年前

    struct 而不是 class

    SomeStruct[] a = new SomeStruct [1000];
    a[0].val1 = 0;
    a[0].val2 = 1;
    a[0].val3 = 2.0;
    ...
    a[999].val1 = 0;
    a[999].val2 = 1;
    a[999].val3 = 2.0;
    

    a 作为 static readonly .

        3
  •  0
  •   Mark H    15 年前

    IEnumerable<> )初始化语法中使用的每个项都将转换为对的调用 .Add(...)

    public class SomeStructCollection : IEnumerable<SomeStruct> {
        private readonly SomeStruct[] someStructs = new SomeStruct[1000];
        private int currentIndex;
    
        public void Add(int val1, int val2, double val3) {
            someStructs[currentIndex++] = new SomeStruct(val1, val2, val3);
        }
    
        public SomeStruct this[int index] {
            get { return someStructs[index];
        }
    
        //Implement IEnumerable<> interface.
    }
    

    SomeStructCollection coll = new SomeStructCollection {
        {0, 0, 0.0}, {1, 1, 1.0}, { ... },
    };