< C++ .NET Arrays & Collections 7 | Main | C++ .NET Arrays & Collections 9 >


 

 

Arrays and Collections 8

 

 

What we have in this page?

 

  1. Array.BinarySearch Method (Array, Object) Example (continue)

 

 

The following code example demonstrates the Exists generic method and several other generic methods that use the Predicate generic delegate. An array of strings is created, containing 8 dinosaur names, two of which (at positions 1 and 5) end with "saurus". The code example also defines a search predicate method named EndsWithSaurus, which accepts a string parameter and returns a Boolean value indicating whether the input string ends in "saurus".

The Exists method stops and returns true at the first element for which the predicate method returns true, which in this case is "Amargasaurus". In C# and Visual Basic, it is not necessary to create the Predicate<string> delegate (Predicate(Of String) in Visual Basic) explicitly. These languages infer the correct delegate from context and create it automatically. The TrueForAll generic method stops and returns false at the first element for which the predicate method returns false. The Find generic method traverses the array from the beginning, passing each element in turn to the EndsWithSaurus method. The search stops when the EndsWithSaurus method returns true for the element "Amargasaurus". The FindLast generic method is used to search the array backward from the end. It finds the element "Dilophosaurus" at position 5. The FindAll generic method is used to return an array containing all the elements that end in "saurus". The elements are displayed.

// SysArray.cpp : main project file.

#include "stdafx.h"

 

using namespace System;

 

// Search predicate returns

// true if a string ends in "saurus".

bool EndsWithSaurus(String^ s)

{

      if ((s->Length > 5) &&

        (s->Substring(s->Length - 6)->ToLower() == "saurus"))

    { return true; }

    else

    { return false; }

};

 

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

{

      array<String^>^ dinosaurs =

      { "Compsognathus", "Amargasaurus", "Oviraptor",

        "Velociraptor", "Deinonychus", "Dilophosaurus",

        "Gallimimus", "Triceratops", "Stupidaurus" };

 

    Console::WriteLine("Our Dinasours");

    Console::WriteLine();

    for each(String^ dinosaur in dinosaurs)

      Console::WriteLine(dinosaur);

 

    Console::WriteLine("\nArray::Exists(dinosaurs, EndsWithSaurus): {0}",

        Array::Exists(dinosaurs, gcnew Predicate<String^>(EndsWithSaurus)));

    Console::WriteLine("\nArray::TrueForAll(dinosaurs, EndsWithSaurus): {0}",

        Array::TrueForAll(dinosaurs, gcnew Predicate<String^>(EndsWithSaurus)));

    Console::WriteLine("\nArray::Find(dinosaurs, EndsWithSaurus): {0}",

        Array::Find(dinosaurs, gcnew Predicate<String^>(EndsWithSaurus)));

    Console::WriteLine("\nArray::FindLast(dinosaurs, EndsWithSaurus): {0}",

        Array::FindLast(dinosaurs, gcnew Predicate<String^>(EndsWithSaurus)));

    Console::WriteLine("\nArray::FindAll(dinosaurs, EndsWithSaurus):");

    array<String^>^ subArray = Array::FindAll(dinosaurs, gcnew Predicate<String^>(EndsWithSaurus));

 

    for each(String^ dinosaur in subArray)

    {

        Console::WriteLine(dinosaur);

    }

    return 0;

}

 

Output:

A code example demonstrates the Exists generic method and several other generic methods that use the Predicate generic delegate

 

The following example shows how resizing affects the array.

// SysArray.cpp : main project file.

#include "stdafx.h"

 

using namespace System;

 

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

{

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

    {

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

    }

    Console::WriteLine();

}

 

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

{

    // Create and initialize a new string array.

    array<String^>^myArr = {L"The", L"quick", L"brown", L"fox", L"jumps", L"over", L"the", L"lazy", L"dog"};

    // Display the values of the array.

    Console::WriteLine(L"The string array initially contains:");

    PrintIndexAndValues(myArr);

    // Resize the array to a bigger size (five elements larger).

    Array::Resize(myArr, myArr->Length + 5);

    // Display the values of the array.

    Console::WriteLine(L"After resizing to a larger size, ");

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

    PrintIndexAndValues(myArr);

    // Resize the array to a smaller size (four elements).

    Array::Resize(myArr, 4);

    // Display the values of the array.

    Console::WriteLine(L"After resizing to a smaller size, ");

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

    PrintIndexAndValues(myArr);

    return 0;

}

 

Output:

 

The string array initially contains:

 [0] : The

 [1] : quick

 [2] : brown

 [3] : fox

 [4] : jumps

 [5] : over

 [6] : the

 [7] : lazy

 [8] : dog

 

After resizing to a larger size,

the string array contains the following values:

 [0] : The

 [1] : quick

 [2] : brown

 [3] : fox

 [4] : jumps

 [5] : over

 [6] : the

 [7] : lazy

 [8] : dog

 [9] :

 [10] :

 [11] :

 [12] :

 [13] :

 

After resizing to a smaller size,

the string array contains the following values:

 [0] : The

 [1] : quick

 [2] : brown

 [3] : fox

Press any key to continue . . .

 

The following code example shows how to reverse the sort of the values in an Array.

// SysArray.cpp : main project file.

#include "stdafx.h"

 

using namespace System;

 

void PrintIndexAndValues(Array^ myArray);

 

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

{

      // Creates and initializes a new Array instance.

      Array^ myArray = Array::CreateInstance(String::typeid, 8);

      myArray->SetValue("The", 0);

      myArray->SetValue("seven", 1);

      myArray->SetValue("layer", 2);

      myArray->SetValue("of", 3);

      myArray->SetValue("the", 4);

      myArray->SetValue("TCP", 5);

      myArray->SetValue("IP", 6);

      myArray->SetValue("stack", 7);

      // Displays the values of the Array.

      Console::WriteLine("The Array instance initially contains:");

      PrintIndexAndValues(myArray);

      // Reverses the sort of the values of the Array.

      Array::Reverse(myArray);

      // Displays the values of the Array.

      Console::WriteLine("After reversing:");

      PrintIndexAndValues(myArray);

 

      return 0;

}

 

void PrintIndexAndValues(Array^ myArray)

{

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

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

}

 

Output:

A code example shows how to reverse the sort of the values in an Array  

 

The following code example shows how to sort the values in an Array using the default comparer and a custom comparer that reverses the sort order. Note that the result might vary depending on the current CultureInfo.

 

// SysArray.cpp : main project file.

#include "stdafx.h"

 

using namespace System;

using namespace System::Collections;

 

public ref class myReverserClass: public IComparer

{

   private:

       // Calls CaseInsensitiveComparer::Compare

       // with the parameters reversed.

       virtual int Compare(Object^ x, Object^ y) = IComparer::Compare

       {

         return ((gcnew CaseInsensitiveComparer)->Compare(y, x));

       }

};

 

void PrintIndexAndValues(array<String^>^myArr)

{

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

   {

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

   }

   Console::WriteLine();

}

 

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

{

      // Creates and initializes a new Array and a new custom comparer.

      array<String^>^myArr = {"Learning","Programming","The","Never","Ending","Story"};

      IComparer^ myComparer = gcnew myReverserClass;

      // Displays the values of the Array.

      Console::WriteLine("The Array initially contains:");

      PrintIndexAndValues(myArr);

      // Sorts a section of the Array using the default comparer.

      Array::Sort(myArr, 1, 3);

      Console::WriteLine("After sorting a section of the\nArray using the default comparer:");

      PrintIndexAndValues(myArr);

      // Sorts a section of the Array using the

      // reverse case-insensitive comparer.

      Array::Sort(myArr, 1, 3, myComparer);

      Console::WriteLine("After sorting a section of the Array using\n"

            "the reverse case-insensitive comparer:");

      PrintIndexAndValues(myArr);

      // Sorts the entire Array using the default comparer.

      Array::Sort(myArr);

      Console::WriteLine("After sorting the entire Array using\nthe default comparer:");

      PrintIndexAndValues(myArr);

      // Sorts the entire Array using the reverse case-insensitive comparer.

      Array::Sort(myArr, myComparer);

      Console::WriteLine("After sorting the entire Array using the reverse\ncase-insensitive comparer:");

      PrintIndexAndValues(myArr);

      return 0;

}

 

Output:

 

The Array initially contains:

[0] : Learning

[1] : Programming

[2] : The

[3] : Never

[4] : Ending

[5] : Story

 

After sorting a section of the

Array using the default comparer:

[0] : Learning

[1] : Never

[2] : Programming

[3] : The

[4] : Ending

[5] : Story

 

After sorting a section of the Array using

the reverse case-insensitive comparer:

[0] : Learning

[1] : The

[2] : Programming

[3] : Never

[4] : Ending

[5] : Story

 

After sorting the entire Array using

the default comparer:

[0] : Ending

[1] : Learning

[2] : Never

[3] : Programming

[4] : Story

[5] : The

 

After sorting the entire Array using the reverse

case-insensitive comparer:

[0] : The

[1] : Story

[2] : Programming

[3] : Never

[4] : Learning

[5] : Ending

 

Press any key to continue . . .

 

 

 

 

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

 


 

< C++ .NET Arrays & Collections 7 | Main | C++ .NET Arrays & Collections 9 >