C++ Builder中的System::DynamicArray动态数组

C++Builder里面有动态数组,使用如下:

//==============================================

//数组长度

DynamicArray<int> arrayOfInt;
arrayOfInt.Length = 10;
cout << "ArrayLength: " << arrayOfInt.Length << endl;

//==============================================


释放数组,只有把长度设置为0即可,不可使用delete删去:

 

//==============================================

arrayOfInt.Length = 0;

//==============================================


访问数据:

void InitArray(DynamicArray<char> &c_array)
{
  c_array[0] = 'A';
  c_array[1] = 'B';
  cout << "Third char is: " << c_array[2];
}

//==============================================


 Low和 High 属性表示数组的上下边界

例如数组求和的函数:

int TotalArray(const DynamicArray<int>& arrayOfInt)
{
  int total=0;
  for (int i=arrayOfInt.Low; i<=arrayOfInt.High; i++)
    total += arrayOfInt[i];
  return total;
}
当然也可以这样:

for (int i=0; i<arrayOfInt.Length; i++)

{

total += arrayOfInt[i];

}

//==================================================


赋值,比较和复制动态数组:

Dynamic Arrays are reference counted. When a DynamicArray is assigned to another, only the reference is assigned (and the reference count adjusted), the content of the source is not copied. Similarly, when two Dynamic Arrays are compared, only the references are compared, not the contents. To copy the contents of a DynamicArray, you must use the Copy (or CopyRange) methods.

//C++ example

void foo(DynamicArray<int> &i_array)
{
  DynamicArray<int> temp = i_array;//此处是引用赋值,不复制数据
  assert(temp == i_array); // temp 和i_array 指向同一内存数据块
  i_array[0] = 20;//此处改变,实际上就是Temp的值
  assert(temp[0] == 20); // Temp的值同样也会改变
  temp = i_array.Copy(); // 赋值数组,此时temp 和i_array 指向不同内存块,
//但是这两个内存所含数据相同
  temp[0] = 10;//此时改变temp的值不会改变i_array的值
  assert(temp[0] != i_array[0]); // Above assignment did not
                                 // modify i_array.
}
//=====================================================

Multidimensional dynamic arrays(多维数组)
例如2维数组,注意该2维数组可以不是方阵数组,
即数组可以由10行,但每一行的元素个数可以不相同
typedef DynamicArray< DynamicArray < AnsiString > > T2DStringArray;
void foo(T2DStringArray &s_array)
{
  SetLength(s_array, 10);
  for (int i=0; i<s_array.Length; i++)
  { // Set lengths of second dimensions.(NOTE: non-rectangular)
    SetLength(s_array[i], i+1);
    for (int j=0; j<s_array[i].Length; j++)
      s_array[i][j] = itoa(i*10+j);
  }
}

//=====================================================

你可能感兴趣的:(C++,Arrays)