5.2. The Array Is a System.Array

All C# array types have access to the System.Array class public methods and properties. For example, the Length property returns the number of elements in an array:

for ( int ix = 0; ix < fib.Length; ++ix )

If the array is multidimensional, Length is a less useful property. For example, for the following array declaration:

static float [,] mat = new float[4,5]
{
      { 1f, 0f, 0f, 0f, 0f },
      { 0f, 1f, 0f, 0f, 0f },
      { 0f, 0f, 1f, 0f, 0f },
      { 0f, 0f, 0f, 1f, 0f }
};

the result of Length is 20. To retrieve the length of the individual dimensions of a multidimensional array, we use GetLength(int dim), where dim represents the number of the dimension: 0, 1, 2, and so on. To discover the number of dimensions associated with an array, we query its Rank property:

int rank = mat.Rank;
Console.WriteLine( "Array of {0} dimensions", rank );

for ( int dim = 1, ix = 0; ix < rank; ++ix )
{
    dim = mat.GetLength( ix );
    Console.WriteLine( "size of dimension {0} is {1} elements",
                        ix, dim );
}

When compiled and executed, this code generates the following output:

Array of 2 dimensions
      size of dimension 0 is 4 elements
      size of dimension 1 is 5 elements

The CopyTo() member function copies the elements of a one-dimensional array into a second array passed in as the first argument. Copying begins in the target array at the index specified as the second argument. If the index is invalid or the target array is too small, an exception is thrown—for example,

int [] fib;

// assign fib to an array ...
int [] notfib = new int[ fib.Length ];
fib.CopyTo( notfib, 0 );

To copy a range of elements from one one-dimensional array to another, we must use the static Copy() method. We pass in the source array, target array, and number of elements to copy. Copying begins at the first elements of both arrays—for example,

Array.Copy( fib, notfib, fib.Length );

If we wish to start copying somewhere other than at the first element of either of the two arrays, we must invoke the five-parameter instance of Copy(). For example, the following invocation copies Length-1 elements of fib beginning at index 1 into notfib beginning at its first element:

Array.Copy( fib, 1, notfib, 0, fib.Length-1 );

If the two arrays hold elements of different types and an implicit conversion exists between those types, the conversion is carried out as part of Copy().

To reset all or a portion of an array to 0 (for the numeric types), false (for the bool type), or null (for a reference type), we invoke the static Clear(). For example, the following invocation zeros out our fib array starting at index 0 for the length of the array:

Array.Clear( fib, 0, fib.Length );

We can sort, reverse, and search one-dimensional arrays as well. For example, consider the following integer array:

int [] ivalues = new int[]{ 14, 8, 2, 16, 8, 7, 14, 0 };

To search for the first occurrence of 8, we use the static IndexOf() method:

int index = Array.IndexOf( ivalues, 8 );

if ( index != -1 ) /* found! */ ;

If the value is found, IndexOf() returns the index of its first occurrence; otherwise it returns -1. LastIndexOf() searches for the last occurrence of the search value, returning either the index or -1.

The following code sequence finds all occurrences of a value. The trick is to invoke IndexOf() repeatedly until it returns -1. To do that, we pass in, as a third parameter, the index at which to begin its search. We begin at 0, of course, and then increment one beyond each matching index:

int index = -1;
ArrayList found = new ArrayList();

while( true )
{
    index = Array.IndexOf( ivalues, search_value, index+1 );

    if ( index == -1 )
         break;

    found.Add( index );
}

Console.Write( "{0} occurrences of {1} found at ",
                found.Count, search_value );

foreach ( int ix in found )
          Console.Write( "{0} ", ix );

When search_value is 8, this code results in the following output:

2 occurrences of 8 found at 1 4

The IndexOf() search algorithm is linear; that is, it looks at each element of the array in turn until either a match is achieved or all the elements have been examined. For large arrays, a binary search is more efficient, but it requires our array to be sorted:

Array.Sort( ivalues );
index = Array.BinarySearch( ivalues, search_value );
if ( index >= 0 ) /* found! */

BinarySearch() returns the value's index, if present; otherwise, it returns a negative value rather than always returning –1. There is also a Reverse() static method. It reverses the order of the elements in the array.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.220.152.139