< C++ .NET Arrays & Collections 6 | Main | C++ .NET Arrays & Collections 8 >


 

 

Arrays and Collections 7

 

 

What we have in this page?

 

  1. Array.AsReadOnly Generic Method Example

  2. Array.BinarySearch Method Example

  3. Array.BinarySearch Method (Array, Object) Example

 

 

Array.AsReadOnly Generic Method Example

 

Let try a few program examples that implement Array class members. The Array::AsReadOnly method returns a read-only wrapper for the specified array. The syntax and the description are summarized in the following Table.

 

Syntax

public:

generic<typename T>

static ReadOnlyCollection<T>^ AsReadOnly (array<T>^ array)

Type Parameters

 

T

The type of the elements of the array.

 

 

Parameters

 

array

The one-dimensional, zero-based array to wrap in a read-only ReadOnlyCollection wrapper.

 

 

Return Value

A read-only ReadOnlyCollection wrapper for the specified array.

 

 

Exceptions

 

Exception type

Condition

ArgumentNullException

array is a null reference (Nothing in Visual Basic).

 

Table 6

 

To prevent any modifications to the array, expose the array only through this wrapper. A collection that is read-only is simply a collection with a wrapper that prevents modifying the collection; therefore, if changes are made to the underlying collection, the read-only collection reflects those changes. This method is an O(1) operation. The following example wraps an array in a read-only ReadOnlyCollection.

// SysArray.cpp : main project file.

#include "stdafx.h"

using namespace System;

using namespace System::Collections::Generic;

 

namespace Samples

{

  public ref class SamplesArray

  {

    public:

     static void Work()

     {

        // Create and initialize a new string array.

        array <String^>^ textArray = {"The", "quick", "brown", "fox"};

        // Display the values of the array.

        Console::WriteLine("The string array initially contains the following values:");

        PrintIndexAndValues(textArray);

        // Create a read-only IList wrapper around the array.

        IList <String^>^ textList = Array::AsReadOnly(textArray);

        // Display the values of the read-only IList.

        Console::WriteLine("The read-only IList contains the following values:");

        PrintIndexAndValues(textList);

        // Attempt to change a value through the wrapper.

        try

        {

          textList[3] = "CAT";

        }

        catch (NotSupportedException^ ex)

        {

          Console::WriteLine("{0} - {1}", ex->GetType(), ex->Message);

          Console::WriteLine();

        }

        // Change a value in the original array.

        textArray[2] = "RED";

        // Display the values of the array.

        Console::WriteLine("After changing the third element,\n"

                 "the string array contains the following values:");

        PrintIndexAndValues(textArray);

        // Display the values of the read-only IList.

        Console::WriteLine("After changing the third element,\nthe"

                 " read-only IList contains the following values:");

        PrintIndexAndValues(textList);

     }

     static void PrintIndexAndValues(array<String^>^ textArray)

     {

         for (int i = 0; i < textArray->Length; i++)

           Console::WriteLine("   [{0}] : {1}", i, textArray[i]);

         Console::WriteLine();

     }

     static void PrintIndexAndValues(IList<String^>^ textList)

     {

         for (int i = 0; i < textList->Count; i++)

           Console::WriteLine("   [{0}] : {1}", i, textList[i]);

         Console::WriteLine();

     }

    };

}

 

int main(array<System::String ^> ^args)

{

  Samples::SamplesArray::Work();

  return 0;

}

 

Output:

An C++ .NET example that wraps an array in a read-only ReadOnlyCollection

 

Array.BinarySearch Method Example

 

This method searches a one-dimensional sorted Array for a value, using a binary search algorithm. The overloaded list is shown in the following Table.

 

Name

Description

Array.BinarySearch (Array, Object)

Searches an entire one-dimensional sorted Array for a specific element, using the IComparable interface implemented by each element of the Array and by the specified object. Supported by the .NET Compact Framework.

Array.BinarySearch (Array, Object, IComparer)

Searches an entire one-dimensional sorted Array for a value using the specified IComparer interface.

Array.BinarySearch (Array, Int32, Int32, Object)

Searches a range of elements in a one-dimensional sorted Array for a value, using the IComparable interface implemented by each element of the Array and by the specified value.

Array.BinarySearch (Array, Int32, Int32, Object, IComparer)

Searches a range of elements in a one-dimensional sorted Array for a value, using the specified IComparer interface. Supported by the .NET Compact Framework.

Array.BinarySearch (T[], T)

Searches an entire one-dimensional sorted Array for a specific element, using the IComparable generic interface implemented by each element of the Array and by the specified object. Supported by the .NET Compact Framework.

Array.BinarySearch (T[], T, Generic IComparer)

Searches an entire one-dimensional sorted Array for a value using the specified IComparer generic interface. Supported by the .NET Compact Framework.

Array.BinarySearch (T[], Int32, Int32, T)

Searches a range of elements in a one-dimensional sorted Array for a value, using the IComparable generic interface implemented by each element of the Array and by the specified value. Supported by the .NET Compact Framework.

Array.BinarySearch (T[], Int32, Int32, T, Generic IComparer)

Searches a range of elements in a one-dimensional sorted Array for a value, using the specified IComparer generic interface. Supported by the .NET Compact Framework.

 

Table 7

 

Array.BinarySearch Method (Array, Object) Example

 

This method searches an entire one-dimensional sorted Array for a specific element, using the IComparable interface implemented by each element of the Array and by the specified object. The syntax and related information are shown in the following Table.

 

Syntax

public:

static int BinarySearch (Array^ array, Object^ value)

Parameters

array

The sorted one-dimensional Array to search.

value

The object to search for.

Return Value

The index of the specified value in the specified array, if value is found. If value is not found and value is less than one or more elements in array, a negative number which is the bitwise complement of the index of the first element that is larger than value. If value is not found and value is greater than any of the elements in array, a negative number which is the bitwise complement of (the index of the last element plus 1).

 

Table 8

 

 

Exceptions

Exception type

Condition

ArgumentNullException

array is a null reference (Nothing in Visual Basic).

RankException

array is multidimensional.

ArgumentException

value is of a type that is not compatible with the elements of array.

InvalidOperationException

value does not implement the IComparable interface, and the search encounters an element that does not implement the IComparable interface.

 

Table 9

 

array must be sorted before calling this method. If the Array does not contain the specified value, the method returns a negative integer. You can apply the bitwise complement operator (~) to the negative result (in Visual Basic, XOR the negative result with -1) to produce an index. If this index is greater than or equal to the size of the array, there are no elements larger than value in the array. Otherwise, it is the index of the first element that is larger than value. Either value or every element of array must implement the IComparable interface, which is used for comparisons. The elements of array must already be sorted in increasing value according to the sort order defined by the IComparable implementation; otherwise, the result might be incorrect.

If value does not implement the IComparable interface, the elements of array are not tested for IComparable before the search begins. An exception is thrown if the search encounters an element that does not implement IComparable. Duplicate elements are allowed. If the Array contains more than one element equal to value, the method returns the index of only one of the occurrences, and not necessarily the first one. A null reference (Nothing in Visual Basic) can always be compared with any other reference type; therefore, comparisons with a null reference (Nothing in Visual Basic) do not generate an exception. When sorting, a null reference (Nothing in Visual Basic) is considered to be less than any other object. For every element tested, value is passed to the appropriate IComparable implementation, even if value is a null reference (Nothing in Visual Basic). That is, the IComparable implementation determines how a given element compares to a null reference (Nothing in Visual Basic). This method is an O(log n) operation, where n is the Length of array. The following code example shows how to use BinarySearch to locate a specific object in an Array. The array is created with its elements in ascending sort order. The BinarySearch method requires the array to be sorted in ascending order.

// SysArray.cpp : main project file.

#include "stdafx.h"

using namespace System;

 

void FindMyObject(Array^ myArr, Object^ myObject);

void PrintValues(Array^ myArr);

 

int main(array<System::String ^> ^args)

{

   // Creates and initializes a new Array instance.

   Array^ myIntArray = Array::CreateInstance(Int32::typeid, 5);

   for (int i = myIntArray->GetLowerBound(0); i <= myIntArray->GetUpperBound(0); i++)

      myIntArray->SetValue(i * 4, i);

   // Displays the values of the Array.

   Console::WriteLine("The Int32 array contains:");

   PrintValues(myIntArray);

   // Locates a specific object that does not exist in the Array.

   Object^ myObjectOdd = 3;

   FindMyObject(myIntArray, myObjectOdd);

   // Locates an object that exists in the Array.

   Object^ myObjectEven = 8;

   FindMyObject(myIntArray, myObjectEven);

   return 0;

}

 

void FindMyObject(Array^ myArr, Object^ myObject)

{

  int myIndex = Array::BinarySearch(myArr, myObject);

 

  Console::WriteLine();

  if (myIndex < 0)

  {

    Console::WriteLine("The object to search for ({0}) is not found.\nThe next larger object is at index {1}.", myObject, ~myIndex);

    Console::WriteLine();

  }

  else

    Console::WriteLine("The object to search for ({0}) is at index {1}.", myObject, myIndex);

}

 

void PrintValues(Array^ myArr)

{

   System::Collections::IEnumerator^ myEnumerator = myArr->GetEnumerator();

   int i = 0;

   int cols = myArr->GetLength(myArr->Rank - 1);

 

   while (myEnumerator->MoveNext())

   {

     if (i < cols)

       i++;

     else

     {

       Console::WriteLine();

       i = 1;

     }

     Console::Write("{0}\t", myEnumerator->Current);

   }

   Console::WriteLine();

}

 

Output:

A code example shows how to use BinarySearch to locate a specific object in an Array  

 

The following code example clones a System::Globalization::CultureInfo array and demonstrates the behavior of a shallow copy.

// SysArray.cpp : main project file.

#include "stdafx.h"

 

using namespace System;

using namespace System::Globalization;

void PrintIndexAndValues(Array^ myArray);

 

int main(array<System::String ^> ^args)

{

      // Create and initialize a new CultureInfo array.

      CultureInfo^ ci0 = gcnew CultureInfo("ar-SA",false);

      CultureInfo^ ci1 = gcnew CultureInfo("en-US",false);

      CultureInfo^ ci2 = gcnew CultureInfo("fr-FR",false);

      CultureInfo^ ci3 = gcnew CultureInfo("ja-JP",false);

      array<CultureInfo^>^arrCI = {ci0,ci1,ci2,ci3};

      // Create a clone of the CultureInfo array.

      array<CultureInfo^>^arrCIClone = (array<CultureInfo^>^)arrCI->Clone();

      // Replace an element in the clone array.

      CultureInfo^ ci4 = gcnew CultureInfo("th-TH",false);

      arrCIClone[0] = ci4;

      // Display the contents of the original array.

      Console::WriteLine("The original array contains the following values:");

      PrintIndexAndValues(arrCI);

      // Display the contents of the clone array.

      Console::WriteLine("The clone array contains the following values:");

      PrintIndexAndValues(arrCIClone);

      // Display the DateTimeFormatInfo.DateSeparator

      // for the fourth element in both arrays.

      Console::WriteLine("Before changes to the clone:");

      Console::WriteLine("   Original: The DateTimeFormatInfo->DateSeparator"

            " for {0} is {1}.", arrCI[3]->Name, arrCI[3]->DateTimeFormat->DateSeparator);

      Console::WriteLine("      Clone: The DateTimeFormatInfo->DateSeparator"

            " for {0} is {1}.", arrCIClone[3]->Name, arrCIClone[3]->DateTimeFormat->DateSeparator);

      // Replace the DateTimeFormatInfo.DateSeparator

      // for the fourth element in the clone array.

      arrCIClone[ 3 ]->DateTimeFormat->DateSeparator = "-";

      // Display the DateTimeFormatInfo.DateSeparator

      // for the fourth element in both arrays.

      Console::WriteLine("After changes to the clone:");

      Console::WriteLine("   Original: The DateTimeFormatInfo->DateSeparator"

            " for {0} is {1}.", arrCI[3]->Name, arrCI[3]->DateTimeFormat->DateSeparator);

      Console::WriteLine("      Clone: The DateTimeFormatInfo->DateSeparator"

            " for {0} is {1}.", arrCIClone[3]->Name, arrCIClone[3]->DateTimeFormat->DateSeparator);

      return 0;

}

 

void PrintIndexAndValues(Array^ myArray)

{

  for (int i = myArray->GetLowerBound(0); i <= myArray->GetUpperBound(0); i++)

    Console::WriteLine("\t[{0}]:\t{1}", i, myArray->GetValue(i));

}

 

Output:

A code example clones a System::Globalization::CultureInfo array and demonstrates the behavior of a shallow copy

 

 

 

 

Part 1 | Part 2 | Part 3 | Part 4 | Part 5 | Part 6 | Part 7 | Part 8

 


 

< C++ .NET Arrays & Collections 6 | Main | C++ .NET Arrays & Collections 8 >