Home

Introduction to Collections

 

Array-Based Lists

 

Introduction

A collection, also called a list, is many items of the same kind grouped into one entity. The collection can be based on simple numbers, basic symbols, dates, strings, times. The collection can also be made of object that each is made of internal values. This means that a collection can be made of such objects as houses, people, cars, countries, electronic devices. The primary rule is all items included in a list must be described using the same characteristics. Based on this, if the collection is made of cars, it should contain only cars, not cars and countries.

There are various types of collections or collections. An array-based list is one whose count is known in advance. For example, a array-based collection of 10 cars contains 10 cars, may-be less but not more.

Setting Up a Collection

To use a collection as an entity, you can create a class for it; this class would be used to add items in the collection, to remove items in the list, or to perform other necessary operations. You can start from a simple class as follows:

public ref class CCollection
{
};

After creating the class for a collection, the collection becomes an object and its class can be used like any other. This means that, before the collection, you can declare a variable for it here is an example:

using namespace System;

public ref class CCollection
{
};

int main()
{
    CCollection ^ list = gcnew CCollection;

    return 0;
}

The Number of Items in a Collection

For an array-based list, because you must specify the number of items that the list will contain, you can declare an array as a member variable. Here is an example:

public ref class CCollection
{
private:
    // This collection will be a list of decimal numbers
    static array<double> ^ Item = gcnew array<double>(20);

public:
    // Our default constructor, used to initialize the collection
    CCollection()
    {
    }
}

Although you can initialize a static array in a C++ class, remember that you can also use a constructor to initialize it. Here is an example:

using namespace System;

int MaxCount = 20;

public ref class CCollection
{
private:
    // This collection will be a list of decimal numbers
    array<double> ^ Item;

public:
    CCollection();
};

CCollection::CCollection()
{
    Item = gcnew array<double>(MaxCount);
}

A primary accessory you need when using a list is a count of the number of items in the list when they are added or deleted. This accessory is primarily a private field as a simple natural number. When the class is declared, this member variable should be set to 0 to indicate that the list is primarily empty:

int MaxCount = 20;

public ref class CCollection
{
private:
    // This collection will be a list of decimal numbers
    array<double> ^ Item;


private:
    // This is the size of the collection
    int size;

public:
    CCollection();
};

CCollection::CCollection()
{
    Item = gcnew array<double>(MaxCount);
    size = 0;
}

Since the size member variable was declared private, if you plan to get the count of items in the list from outside the class, you can provide a property to take care of this-> This can simply be done as follows:

using namespace System;

int MaxCount = 20;

public ref class CCollection
{
private:
    // This collection will be a list of decimal numbers
    array<double> ^ Item;

private:
    // This is the size of the collection
    int size;

public:
    // This represents the number of items in the collection
    property int Count
    {
        int get() { return size; }
    }

public:
    CCollection();
};

CCollection::CCollection()
{
    Item = gcnew array<double>(MaxCount);
    size = 0;
}

int main()
{
    CCollection ^ list = gcnew CCollection;

    Console::WriteLine(L"Number of Items: {0}", list->Count);

    return 0;
}

This would produce:

Number of Items: 0
Press any key to continue . . .

Operations on an Array-Based List

 

Adding an Item

Creating a collection consists of adding items to it. Items are usually added one at a time. The easiest way to do this is to add an item at the end of the existing collection.

To add an item to the collection, you first check whether the list is already full. For an array-based list, the collection is full if its count of items is equal to or higher than the maximum number you had set. If the collection is not empty, you can add an item at the end and increase the count by one. Here is how this can be done:

using namespace System;

int MaxCount = 20;

public ref class CCollection
{
private:
    // This collection will be a list of decimal numbers
    array<double> ^ Item;

private:
    // This is the size of the collection
    int size;

public:
    // This represents the number of items in the collection
    property int Count
    {
        int get() { return size; }
    }
    
    bool Add(double item);

public:
    CCollection();
};

CCollection::CCollection()
{
    Item = gcnew array<double>(MaxCount);
    size = 0;
}

// Adds a new item to the list if the list is not full
// Increases the number of items in the list
// Returns true if the item was added, otherwise returns false
bool CCollection::Add(double item)
{
    // Make sure the list is not yet full
    if (size < 20)
    {
        // Since the list is not full, add the "item" at the end
        Item[size] = item;
        // Increase the count and return the new position
        size++;

        // Indicate that the item was successfully added
        return true;
    }

    // If the item was not added, return false;
    return false;
}

Once you have a means of adding items to the list, you can effectively create a list of items. Here is an example:

int main()
{
    CCollection ^ list = gcnew CCollection;

    Console::WriteLine(L"Number of Items: {0}", list->Count);

    list->Add(224.52);
    list->Add(60.48);
    list->Add(1250.64);
    list->Add(8.86);
    list->Add(1005.36);

    Console::WriteLine(L"Number of Items: {0}", list->Count);
    return 0;
}

This would produce:

Number of Items: 0
Number of Items: 5
Press any key to continue . . .

Getting an Item From a List

After adding items to a collection, you can retrieve them to do what you intended the list for. To retrieve an item, you can locate it by its position, the same way you would do for an array. Having this index, you can check whether the position specified is negative or higher than the current count of items. If it is, there is nothing much to do since the index would be wrong. If the index is in the right range, you can retrieve its corresponding item. The method to do this can be implemented as follows:

using namespace System;

int MaxCount = 20;

public ref class CCollection
{
private:
    // This collection will be a list of decimal numbers
    array<double> ^ Item;

private:
    // This is the size of the collection
    int size;

public:
    // This represents the number of items in the collection
    property int Count
    {
        int get() { return size; }
    }
    
    bool Add(double item);
    double Retrieve(int pos);

public:
    CCollection();
};

CCollection::CCollection()
{
    Item = gcnew array<double>(MaxCount);
    size = 0;
}

// Adds a new item to the list if the list is not full
// Increases the number of items in the list
// Returns true if the item was added, otherwise returns false
bool CCollection::Add(double item)
{
    // Make sure the list is not yet full
    if (size < 20)
    {
        // Since the list is not full, add the "item" at the end
        Item[size] = item;
        // Increase the count and return the new position
        size++;

        // Indicate that the item was successfully added
        return true;
    }

    // If the item was not added, return false;
    return false;
}

// Retrieves an item from the list based on the specified index
double CCollection::Retrieve(int pos)
{
    // Make sure the index is in the range
    if( (pos >= 0) && (pos <= size) )
        return this->Item[pos];

    // If the index was wrong, return 0
    return 0;
}

int main()
{
    CCollection ^ list = gcnew CCollection;

    Console::WriteLine(L"Number of Items: {0}\n", list->Count);

    list->Add(224.52);
    list->Add(60.48);
    list->Add(1250.64);
    list->Add(8.86);
    list->Add(1005.36);

     for(int i = 0; i < list->Count; i++)
         Console::WriteLine(L"Item {0}: {1}", i + 1, list->Retrieve(i));

    Console::WriteLine(L"\nNumber of Items: {0}", list->Count);

    return 0;
}

This would produce:

Number of Items: 0
Item 1: 224.52
Item 2: 60.48
Item 3: 1250.64
Item 4: 8.86
Item 5: 1005.36
Number of Items: 5

Press any key to continue . . .

Inserting an Item in the List

Inserting a new item in the collection allows you to add one at a position of your choice. To insert an item in the list, you must provide the new item and the desired position. Before performing this operation, you must check two things. First, the list must not be empty. Second, the specified position must be in the allowed range.

The method can be implemented as follows:

using namespace System;

int MaxCount = 20;

public ref class CCollection
{
private:
    // This collection will be a list of decimal numbers
    array<double> ^ Item;

private:
    // This is the size of the collection
    int size;

public:
    // This represents the number of items in the collection
    property int Count
    {
        int get() { return size; }
    }
    
    bool Add(double item);
    double Retrieve(int pos);
    bool Insert(double itm, int pos);

public:
    CCollection();
};

CCollection::CCollection()
{
    Item = gcnew array<double>(MaxCount);
    size = 0;
}

// Adds a new item to the list if the list is not full
// Increases the number of items in the list
// Returns true if the item was added, otherwise returns false
bool CCollection::Add(double item)
{
    // Make sure the list is not yet full
    if (size < 20)
    {
        // Since the list is not full, add the "item" at the end
        Item[size] = item;
        // Increase the count and return the new position
        size++;

        // Indicate that the item was successfully added
        return true;
    }

    // If the item was not added, return false;
    return false;
}

// Retrieves an item from the list based on the specified index
double CCollection::Retrieve(int pos)
{
    // Make sure the index is in the range
    if( (pos >= 0) && (pos <= size) )
        return this->Item[pos];

    // If the index was wrong, return 0
    return 0;
}

// Before performing this operation, check that
// 1. The list is not full
// 2. The specified position is in an allowable range
// Inserts a new item at a specified position in the list
// After the new item is inserted, the count is increased
bool CCollection::Insert(double itm, int pos)
{
    // Check that the item can be added to the list
    if( (size < 20) && (pos >= 0) && (pos <= size) )
    {
        // Since there is room,
        // starting from the end of the list to the new position,
        // push each item to the next or up
        // to create room for the new item
        for(int i = size; i > pos - 1; i--)
            this->Item[i + 1] = this->Item[i];

        // Now that we have room, put the new item in the position created
        Item[pos] = itm;

        // Since we have added a new item, increase the count
        size++;

        // Indicate that the operation was successful
        return true;
    }

    // Since the item could not be added, return false
    return false;
}

int main()
{
    CCollection ^ list = gcnew CCollection;

    Console::WriteLine(L"Number of Items: {0}\n", list->Count);

    list->Add(224.52);
    list->Add(60.48);
    list->Add(1250.64);
    list->Add(8.86);
    list->Add(1005.36);

    for(int i = 0; i < list->Count; i++)
        Console::WriteLine(L"Item {0}: {1}", i + 1, list->Retrieve(i));

    Console::WriteLine(L"\nNumber of Items: {0}\n", list->Count);

    list->Insert(-707.16, 2);

    for(int i = 0; i < list->Count; i++)
        Console::WriteLine(L"Item {0}: {1}", i + 1, list->Retrieve(i));

    Console::WriteLine(L"\nNumber of Items: {0}\n", list->Count);

    return 0;
}

This would produce:

Number of Items: 0
Item 1: 224.52
Item 2: 60.48
Item 3: 1250.64
Item 4: 8.86
Item 5: 1005.36

Number of Items: 5

Item 1: 224.52
Item 2: 60.48
Item 3: -707.16
Item 4: 1250.64
Item 5: 8.86
Item 6: 1005.36
Number of Items: 6

Press any key to continue . . .

Removing an Item From the List

Another operation you can perform on a collection consists of deleting an item. This is also referred to as removing the item. To delete an item from the collection, you can provide its position. Before performing the operation, you can first check that the specified position is valid. The method to perform this operation can be implemented as follows:

using namespace System;

int MaxCount = 20;

public ref class CCollection
{
private:
    // This collection will be a list of decimal numbers
    array<double> ^ Item;

private:
    // This is the size of the collection
    int size;

public:
    // This represents the number of items in the collection
    property int Count
    {
        int get() { return size; }
    }
    
    bool Add(double item);
    double Retrieve(int pos);
    bool Insert(double itm, int pos);
    bool Delete(int pos);

public:
    CCollection();
};

CCollection::CCollection()
{
    Item = gcnew array<double>(MaxCount);
    size = 0;
}

// Adds a new item to the list if the list is not full
// Increases the number of items in the list
// Returns true if the item was added, otherwise returns false
bool CCollection::Add(double item)
{
    // Make sure the list is not yet full
    if (size < 20)
    {
        // Since the list is not full, add the "item" at the end
        Item[size] = item;
        // Increase the count and return the new position
        size++;

        // Indicate that the item was successfully added
        return true;
    }

    // If the item was not added, return false;
    return false;
}

// Retrieves an item from the list based on the specified index
double CCollection::Retrieve(int pos)
{
    // Make sure the index is in the range
    if( (pos >= 0) && (pos <= size) )
        return this->Item[pos];

    // If the index was wrong, return 0
    return 0;
}

// Before performing this operation, check that
// 1. The list is not full
// 2. The specified position is in an allowable range
// Inserts a new item at a specified position in the list
// After the new item is inserted, the count is increased
bool CCollection::Insert(double itm, int pos)
{
    // Check that the item can be added to the list
    if( (size < 20) && (pos >= 0) && (pos <= size) )
    {
        // Since there is room,
        // starting from the end of the list to the new position,
        // push each item to the next or up
        // to create room for the new item
        for(int i = size; i > pos - 1; i--)
            this->Item[i + 1] = this->Item[i];

        // Now that we have room, put the new item in the position created
        Item[pos] = itm;

        // Since we have added a new item, increase the count
        size++;

        // Indicate that the operation was successful
        return true;
    }

    // Since the item could not be added, return false
    return false;
}

// Removes an item from the list
// First check that the specified position is valid
// Deletes the item at that position and decreases the count
bool CCollection::Delete(int pos)
{
    // Make sure the position specified is in the range
    if (pos >= 0 && pos <= size)
    {
        // Since there is room, starting at the specified position,
        // Replace each item by the next
        for (int i = pos; i < this->size; i++)
            this->Item[i] = this->Item[i + 1];

        // Since an item has been removed, decrease the count
        this->size--;

        // Indicate that the operation was successful
        return true;
    }

    // Since the position was out of range, return false
    return false;
}

int main()
{
    CCollection ^ list = gcnew CCollection;

    Console::WriteLine(L"Number of Items: {0}\n", list->Count);

    list->Add(224.52);
    list->Add(60.48);
    list->Add(1250.64);
    list->Add(8.86);
    list->Add(1005.36);

    for(int i = 0; i < list->Count; i++)
        Console::WriteLine(L"Item {0}: {1}", i + 1, list->Retrieve(i));

    Console::WriteLine(L"\nNumber of Items: {0}\n", list->Count);

    list->Insert(-707.16, 2);
    list->Insert(-369952.274, 4);

    for(int i = 0; i < list->Count; i++)
        Console::WriteLine(L"Item {0}: {1}", i + 1, list->Retrieve(i));

    Console::WriteLine(L"\nNumber of Items: {0}\n", list->Count);

    list->Delete(5);
    list->Delete(3);

    for(int i = 0; i < list->Count; i++)
        Console::WriteLine(L"Item {0}: {1}", i + 1, list->Retrieve(i));
    Console::WriteLine(L"\nNumber of Items: {0}\n", list->Count);

    return 0;
}

This would produce:

Number of Items: 0

Item 1: 224.52
Item 2: 60.48
Item 3: 1250.64
Item 4: 8.86
Item 5: 1005.36

Number of Items: 5

Item 1: 224.52
Item 2: 60.48
Item 3: -707.16
Item 4: 1250.64
Item 5: -369952.274
Item 6: 8.86
Item 7: 1005.36

Number of Items: 7

Item 1: 224.52
Item 2: 60.48
Item 3: -707.16
Item 4: -369952.274
Item 5: 1005.36

Number of Items: 5

Press any key to continue . . .

A Collection of Items

 

Introduction

Like an array, a collection is a series of items of the same type. The particularity with creating an array is that you must know in advance the number of items that will make up the list. There are times when you don't know, you can't know, or you can't predict the number of items of the list. For this reason, you may want to create the list for which you don't specify the maximum number of items but you allow the user of the list to add, locate, or remove items at will.

Before creating a list, you probably should first decide or define what the list would be made of. As different as they are, one list can be made of numeric values. For example, a list that will be made of numbers. You may want a list that is made of names. Such a list can be created from a class that includes a string member variable. Another type of list can contain complex objects.

Practical LearningPractical Learning: Introducing Collections

  1. Start Microsoft Visual C++ and create a new CLR Empty Project named FlowerShop4
  2. To create a new class, in the Solution Explorer, right-click FlowerShop4 -> Add -> Class...
  3. In the Templates list, click C++ Class and click Add
  4. Set the Name of the class to CFlower and click Finish
  5. Change the Flower.h header file as follows:
     
    using namespace System;
    
    public enum FlowerType
    {
        Roses = 1,
        Lilies,
        Daisies,
        Carnations,
        LivePlant,
        Mixed
    };
    
    public enum FlowerColor
    {
        Red = 1,
        White,
        Yellow,
        Pink,
        Orange,
        Blue,
        Lavender,
        Various
    };
    Flower
    public enum FlowerArrangement
    {
        Bouquet = 1,
        Vase,
        Basket,
        Any
    };
    
    public ref class CFlower sealed
    {
    private:
        double pc;
    
    public:
        FlowerType Type;
        FlowerColor Color;
        FlowerArrangement Arrangement;
    
        property double UnitPrice
        {
            double get() { return pc; }
            void set(double value) { pc = value; }
        }
    
        CFlower();
    };
    
  6. Access the Flower.cpp source file and change it as follows:
     
    #include "Flower.h"
    
    CFlower::CFlower(void)
    {
        Type = FlowerType::Mixed;
        Color = FlowerColor::Mixed;
        Arrangement = FlowerArrangement::Vase;
        pc = 0.00;
    }
  7. To create a new class, in the Solution Explorer, right-click FlowerShop4 -> Add -> Class...
  8. In the Templates list, click C++ Class and click Add
  9. Set the Name of the class to COrderProcessing and click Add
  10. Complete the OrderProcessing.h header file as follows:
     
    #pragma once
    
    #include "Flower.h"
    
    using namespace System;
    
    public ref class COrderProcessing
    {
    public:
        CFlower ^ FlowerOrder;
       
    private:
        int qty;
    public:
        COrderProcessing(void);
    
        property int Quantity
        {
            int get() { return qty; }
            void set(int value) { qty = value; }
        }
    
        property double TotalPrice
        {
            double get() { return Quantity * FlowerOrder->UnitPrice; }
        }
    
        void GetFlowerType();
        void GetFlowerColor();
        void GetFlowerArrangement();
        void ProcessOrder()
        void ShowOrder();
    };
  11. Access the OrderProcessing.cpp source file and change it as follows:
     
    #include "OrderProcessing.h"
    
    COrderProcessing::COrderProcessing(void)
    {
        FlowerOrder = gcnew CFlower;
    }
    
    void COrderProcessing::GetFlowerType()
    {
        int choice = 0;
    
        do {
            try {
                Console::WriteLine(L"Enter the Type of Flower Order");
                Console::WriteLine(L"1. Roses");
                Console::WriteLine(L"2. Lilies");
                Console::WriteLine(L"3. Daisies");
                Console::WriteLine(L"4. Carnations");
                Console::WriteLine(L"5. Live Plant");
                Console::WriteLine(L"6. Mixed");
                Console::Write("Your Choice: ");
                choice = int::Parse(Console::ReadLine());
            }
            catch(FormatException ^)
            {
                 Console::WriteLine(L"You failed to enter an "
                                    L"appropriate number!");
            }
    
            if ((choice < 1) || (choice > 6))
                Console::WriteLine(L"Invalid Value: Please enter "
                                   L"a value between 1 and 6");
        } while( (choice < 1) || (choice > 6) );
    
        switch(choice)
        {
        case 1:
            FlowerOrder->Type = Roses;
            break;
        case 2:
            FlowerOrder->Type = Lilies;
            break;
        case 3:
            FlowerOrder->Type = Daisies;
            break;
        case 4:
            FlowerOrder->Type = Carnations;
            break;
        case 5:
            FlowerOrder->Type = LivePlant;
            break;
        default:
            FlowerOrder->Type = Mixed;
            break;
        }
    }
    
    void COrderProcessing::GetFlowerColor()
    {
        int choice = 0;
    
        do {
            try {
                Console::WriteLine(L"Enter the Color");
                Console::WriteLine(L"1. Red");
                Console::WriteLine(L"2. White");
                Console::WriteLine(L"3. Yellow");
                Console::WriteLine(L"4. Pink");
                Console::WriteLine(L"5. Orange");
                Console::WriteLine(L"6. Blue");
                Console::WriteLine(L"7. Lavender");
                Console::WriteLine(L"8. Mixed");
                Console::Write("Your Choice: ");
    			choice = int::Parse(Console::ReadLine());
            }
            catch(FormatException ^)
            {
                Console::WriteLine(L"You didn't enter an "
                                   L"appropriate number!");
            }
    
            if( (choice < 1) || (choice > 8) )
                Console::WriteLine(L"Invalid Value: Please "
                                   L"enter a value between 1 and 8");
        } while ((choice < 1) || (choice > 8));
    
        switch(choice)
        {
        case 1:
            FlowerOrder->Color = Red;
            break;
        case 2:
            FlowerOrder->Color = White;
            break;
        case 3:
            FlowerOrder->Color = Yellow;
            break;
        case 4:
            FlowerOrder->Color = Pink;
            break;
        case 5:
            FlowerOrder->Color = Yellow;
            break;
        case 6:
            FlowerOrder->Color = Blue;
            break;
        case 7:
            FlowerOrder->Color = Lavender;
            break;
        default:
            FlowerOrder->Color = Various;
            break;
        }
    }
    
    void COrderProcessing::GetFlowerArrangement()
    {
        int choice = 0;
    
        do {
           try {
                Console::WriteLine(L"Enter the Type of Arrangement");
                Console::WriteLine(L"1. Bouquet");
                Console::WriteLine(L"2. Vase");
                Console::WriteLine(L"3. Basket");
                Console::WriteLine(L"4. Mixed");
                Console::Write("Your Choice: ");
    			choice = int::Parse(Console::ReadLine());
            }
            catch(FormatException ^)
            {
                Console::WriteLine(L"You didn't provide an "
                                   L"acceptable number!");
            }
    
            if( (choice < 1) || (choice > 4) )
                Console::WriteLine(L"Invalid Value: Please enter "
                                   L"a value between 1 and 4");
        } while ((choice < 1) || (choice > 4));
    
        switch (choice)
        {
        case 1:
            FlowerOrder->Arrangement = Bouquet;
            break;
        case 2:
            FlowerOrder->Arrangement = Vase;
            break;
        case 3:
            FlowerOrder->Arrangement = Basket;
            break;
        default:
            FlowerOrder->Arrangement = Any;
            break;
        }
    }
    
    void COrderProcessing::ProcessOrder()
    {
        GetFlowerType();
        GetFlowerColor();
        GetFlowerArrangement();
    
        try {
            Console::Write("Enter the Unit Price: ");
            FlowerOrder->UnitPrice = 
    			Math::Abs(double::Parse(Console::ReadLine()));
        }
        catch(FormatException ^)
        {
            Console::WriteLine(L"You didn't specify a valid price!");
        }
    
        try {
            Console::Write("Enter Quantity:       ");
    		Quantity = Math::Abs(int::Parse(Console::ReadLine()));
        }
        catch(FormatException ^)
        {
            Console::WriteLine(L"The quantity you entered "
                              L"is not acceptable!");
        }
    }
    
    void COrderProcessing::ShowOrder()
    {
        Console::WriteLine(L"=======================");
        Console::WriteLine(L"==-=-=Flower Shop=-=-==");
        Console::WriteLine(L"-----------------------");
        Console::Write(L"Flower Type:  ");
        switch(FlowerOrder->Type)
        {
        case 1:
            Console::WriteLine(L"Roses");
            break;
        case 2:
            Console::WriteLine(L"Lilies");
            break;
        case 3:
            Console::WriteLine(L"Daisies");
            break;
        case 4:
            Console::WriteLine(L"Carnations");
            break;
        case 5:
            Console::WriteLine(L"Live Plant");
    	break;
        default:
    	Console::WriteLine(L"Mixed");
        }
        
        Console::Write(L"Flower Color: ");
        switch(FlowerOrder->Color)
        {
        case 1:
            Console::WriteLine(L"Red");
    	break;
        case 2:
            Console::WriteLine(L"White");
    	break;
        case 3:
            Console::WriteLine(L"Yellow");
    	break;
        case 4:
            Console::WriteLine(L"Pink");
    	break;
        case 5:
            Console::WriteLine(L"Orange");
    	break;
        case 6:
            Console::WriteLine(L"Blue");
    	break;
        case 7:
            Console::WriteLine(L"Lavender");
    	break;
        default:
            Console::WriteLine(L"Various");
        }
    
        Console::Write(L"Arrangement:  ");
        switch(FlowerOrder->Arrangement)
        {
        case 1:
            Console::WriteLine(L"Bouquet");
    	break;
        case 2:
            Console::WriteLine(L"Vase");
    	break;
        case 3:
            Console::WriteLine(L"Basket");
    	break;
        default:
            Console::WriteLine(L"Any");
        }
    
        Console::Write(L"Price:        "); 
        Console::WriteLine(FlowerOrder->UnitPrice);
        Console::Write(L"Quantity:     "); 
        Console::WriteLine(Quantity);
        Console::Write(L"Total Price:  "); 
        Console::WriteLine(TotalPrice.ToString(L"C"));
        Console::WriteLine(L"=======================");
    }
  12. To create a source file, in the Solution Explorer, right-click FlowerShop4 -> Add -> New Item...
  13. In the Templates list, click C++ File (.cpp)
  14. Set the Name to Exercise and click Add
  15. Complete the file as follows:
     
    using namespace System;
    
    int main()
    {
        COrderProcessing ^ order = gcnew OrderProcessing;
    
        order->ProcessOrder();
        Console::WriteLine();
    
        order->ShowOrder();
    
        Console::WriteLine();
        return 0;
    }
  16. Execute the application and test it. Here is an example:
     
    Enter the Type of Flower Order
    1. Roses
    2. Lilies
    3. Daisies
    4. Carnations
    5. Live Plant
    6. Mixed
    Your Choice: 3
    Enter the Color
    1. Red
    2. White
    3. Yellow
    4. Pink
    5. Orange
    6. Blue
    7. Lavender
    8. Mixed
    Your Choice: 8
    Enter the Type of Arrangement
    1. Bouquet
    2. Vase
    3. Basket
    4. Mixed
    Your Choice: 1
    Enter the Unit Price: 45.50
    Enter Quantity:       3
    
    =======================
    ==-=-=Flower Shop=-=-==
    -----------------------
    Flower Type:  Daisies
    Flower Color: Various
    Arrangement:  Bouquet
    Price:        $45.50
    Quantity:     3
    Total Price:  $136.50
    =======================
    
    Press any key to continue . . .
    Daisy
  17. Close the DOS window

Implementing a Collection

After deciding what each item of the list would be made of, you can create a class that would manage the list. This class would be responsible for all operations that can be performed on the list. Here is an example:

using namespace System;

public ref class CNumbers
{
};

int main()
{
    CNumbers ^ nbrs = gcnew CNumbers;

    return 0;
}

If the list will be made of objects, you can first create a class that specifies those types of items and then declare its variable in the list class. Here is an example of a simple class that holds a double-precision value:

using namespace System;

public ref class CNumber
{
public:
    double Item;
};

public ref class CNumbers
{
    CNumber ^ Sample;
};

int main()
{
    CNumbers ^ nbrs = gcnew CNumbers;

    return 0;
}

When creating a list, one of the aspects you should pay attention to is to keep track of the number of items in the list. To do this, you can create a property that holds the number. The value of this property would increase as the items are added to the list and the value would decrease as the items are removed from the list. Here is how this can be done:

using namespace System;

public ref class CNumber
{
public:
    double Item;
};

public ref class CNumbers
{
private:
    int size;
    CNumber ^ Sample;

public:
    CNumbers()
    {
        size = 0;
    }

    property int Count
    {
        int get() { return size; }
    }
};

int main()
{
    CNumbers ^ nbrs = gcnew CNumbers;

    Console::WriteLine(L"Number of Items: {0}", nbrs->Count);

    return 0;
}

This would produce:

Number of Items: 0
Press any key to continue . . .

Practical LearningPractical Learning: Creating a CCollection Class

  1. Open the Flower.h header file and change it as follows:
     
    #pragma once
    
    using namespace System;
    
    . . . No Change
    
    public ref class CFlower
    {
    private:
        double prc;
    
    public:
        FlowerType Type;
        FlowerColor Color;
        FlowerArrangement Arrangement;
    
        property double UnitPrice
        {
            double get() { return prc; }
            void set(double value) { prc = value; }
        }
    
        CFlower(void);
    
    protected:
        int items;
    
    public:
        property int Count
        {
            int get() { return items; }
        }
    };
  2. Open the Flower.cpp source file and change it as follows:
     
    #include "Flower.h"
    
    CFlower::CFlower(void)
    {
        Type        = Mixed;
        Color       = Various;
        Arrangement = Vase;
        prc         = 0.00;
    	
        items       = 0;
    }
  3. To create a new class, in the Class View, right-click FlowerShop4 -> Add -> Class...
  4. In the Templates list, click C++ Class and click Add
  5. Set the Name to CFlowerInventory and click Finish
  6. Change the FlowerInventory.h header file as follows:
     
    #pragma once
    
    #include "Flower.h"
    
    public ref class CFlowerInventory : CFlower
    {
    public:
        CFlower ^ Inventory;
    
        CFlowerInventory(void);
    };
  7. Access the FlowerInventory.cpp source file and change it as follows:
     
    #include "FlowerInventory.h"
    
    CFlowerInventory::CFlowerInventory(void)
    {
        Inventory = gcnew CFlower;
    }

The Beginning of a Collection

A good collection is a list that can grow or shrink as the user wishes. When creating the list, you don't need to predict the maximum number of items that will be added to the list. When a list starts, it is empty or at least it must be considered like that, before any item is added to it. To specify this, you should declare a primary member variable. Although you can call it anything, it is usually called Head. This member can be made private if you don't intend to access it outside of the class. If you want clients of the class to access it, you can make it public. Here is an example:

public ref class CNumbers
{
private:
    int size;
    CNumber ^ Sample;

public:
    CNumber ^ Head;

    CNumbers()
    {
        size = 0;
        Head = nullptr;
    }

    property int Count
    {
        int get() { return size; }
    }
};

Linking the Items of a Collection

When using an array, each member can be accessed using its index. If the items of a collection are not indexed, you must provide a mechanism to locate an item. To do this, you can use a starting point that determines the beginning of the first. Then, to locate an item, you can check whether another item follows that starting point. If no item follows it, either you are at the end of the list or the list is empty.

To be able to scan a list from one item to another, you can declare a member variable. Although this member variable can be called anything, for the sake of clarify, you should call it Next. The member variable is the same type as its class. Here is an example:

public ref class CNumber
{
public:
    double Item;
    CNumber ^ Next;
};

Practical LearningPractical Learning: Creating a List's Monitor

  1. Access the Flower.h header file and change it as follows:
     
    using namespace System;
    
    . . . No Change
    
    public ref class CFlower
    {
    
        . . . No Change
    
    protected:
        int items;
    
    public:
        property int Count
        {
            int get() { return items; }
        }
    
        CFlower ^ Next;
    };
  2. Access the FlowerInventory.h header file and change it as follows:
     
    #pragma once
    
    #include "Flower.h"
    
    public ref class CFlowerInventory : CFlower
    { 
    public:
        CFlower ^ Inventory;
    
        CFlowerInventory(void);
        CFlower ^ Head;
    };
  3. Access the FlowerInventory.cpp source file and change it as follows:
     
    #include "FlowerInventory.h"
    
    CFlowerInventory::CFlowerInventory(void)
    {
        Head = nullptr;
        Inventory = gcnew CFlower;
    }
  4. Save all

Operations on a Collection

 

Adding an Item

The primary operation you can perform on a list is to add a new item to it, since a list is fundamentally empty when it starts. In order to indicate that you want to add an item to the list, you can create a method that receives an item as argument. For the return type, you have two main options. Because the main job of this method is to add a new item, which it hardly fails to do if you implement it right, it can be defined as void. Alternatively, you can make it return the position of the new item in the list. Here is an example:

public ref class CNumbers
{
private:
    int size;
    CNumber ^ Sample;

public:
    CNumber ^ Head;

    CNumbers()
    {
        size = 0;
        Head = nullptr;
    }

    property int Count
    {
        int get() { return size; }
    }

    int Add(CNumber ^ NewItem)
    {
        CNumber ^ Sample = gcnew CNumber;

        Sample = NewItem;
        Sample->Next = Head;
        Head = Sample;
        return size++;
    }
};

int main()
{
    CNumbers ^ nbrs = gcnew CNumbers;

    Console::WriteLine(L"Number of Items: {0}", nbrs->Count);

    CNumber ^ one = gcnew CNumber;
    one->Item = 2937.45;
    nbrs->Add(one);

    one = gcnew CNumber;
    one->Item = 329.459;
    nbrs->Add(one);

    one = gcnew CNumber;
    one->Item = 98.23456;
    nbrs->Add(one);

    one = gcnew CNumber;
    one->Item = 32465.645;
    nbrs->Add(one);

    return 0;
}

Practical LearningPractical Learning: Adding Items to a Collection

  1. Change the FlowerInventory.h header file as follows:
     
    #pragma once
    
    #include "Flower.h"
    
    public ref class CFlowerInventory : CFlower
    { 
    public:
        CFlower ^ Inventory;
    
        CFlowerInventory(void);
        CFlower ^ Head;
    	
        int Add(CFlower ^ obj);
    };
  2. Access the FlowerInventory.cpp source file and change it as follows:
     
    #include "FlowerInventory.h"
    
    CFlowerInventory::CFlowerInventory(void)
    {
        Head = nullptr;
        Inventory = gcnew CFlower;
    }
    
    int CFlowerInventory::Add(CFlower ^ NewFlower)
    {
        CFlower ^ Sample = gcnew CFlower;
    
        Sample = NewFlower;
        Sample->Next = Head;
        Head = Sample;
        return items++;
    }
  3. Save all

Retrieving an Item

Once a list exists, the user can explore it. One of the operations performed on items is to locate and retrieve one. To do this, you can create a method that takes as argument an index. The method would examine the argument with regards to the number of items in the list to make sure the argument's value is in the range of the current items of the list. If the number is too low or too high, the method can return nullptr. If the number is in the range, the method can return the item at that position. Here is an example:

using namespace System;

public ref class CNumber
{
public:
    double Item;
    CNumber ^ Next;
};

public ref class CNumbers
{
private:
    int size;
    CNumber ^ Sample;

public:
    CNumber ^ Head;

    CNumbers()
    {
        size = 0;
        Head = nullptr;
    }

    property int Count
    {
        int get() { return size; }
    }

    int Add(CNumber ^ NewItem)
    {
        CNumber ^ Sample = gcnew CNumber;

        Sample = NewItem;
        Sample->Next = Head;
        Head = Sample;
        return size++;
    }

    CNumber ^ Retrieve(int Position)
    {
        CNumber ^ Current = Head;

        for (int i = Count - 1; i > Position && Current != nullptr; i--)
            Current = Current->Next;
        return Current;
    }
};

int main()
{
    CNumbers ^ nbrs = gcnew CNumbers;

    Console::WriteLine(L"Number of Items: {0}\n", nbrs->Count);

    CNumber ^ one = gcnew CNumber;
    one->Item = 2937.45;
    nbrs->Add(one);one = gcnew CNumber;
    one->Item = 329.459;
    nbrs->Add(one);one = gcnew CNumber;
    one->Item = 98.23456;
    nbrs->Add(one);one = gcnew CNumber;
    one->Item = 32465.645;
    nbrs->Add(one);

    Console::WriteLine(L"\nNumber of Items: {0}\n", nbrs->Count);

    for(int i = 0; i < nbrs->Count; i++)
        Console::WriteLine("Number: {0}", nbrs->Retrieve(i)->Item);

    Console::WriteLine();
    return 0;
}

This would produce:

Number of Items: 0


Number of Items: 4

Number: 2937.45
Number: 329.459
Number: 98.23456
Number: 32465.645

Press any key to continue . . .

Practical LearningPractical Learning: Retrieving the Items of a Collection

  1. Access the FlowerInventory.h header file and add the following method:
     
    #pragma once
    
    #include "Flower.h"
    
    public ref class CFlowerInventory : CFlower
    { 
    public:
        CFlower ^ Inventory;
    
    	CFlowerInventory(void);
        CFlower ^ Head;
    	
        int Add(CFlower ^ obj);
        CFlower ^ Get(int index);
    };
  2. Access the FlowerInventory.cpp source file and add the following method:
     
    #include "FlowerInventory.h"
    
    CFlowerInventory::CFlowerInventory(void)
    {
        Head = nullptr;
        Inventory = gcnew CFlower;
    }
    
    int CFlowerInventory::Add(CFlower ^ NewFlower)
    {
        CFlower ^ Sample = gcnew CFlower;
    
        Sample = NewFlower;
        Sample->Next = Head;
        Head = Sample;
        return items++;
    }
    
    CFlower ^ CFlowerInventory::Get(int index)
    {
        CFlower ^ Current = Head;
    
        for(int i = Count - 1;
            i > index && Current != nullptr;
            i--)
            Current = Current->Next;
        return Current;
    }
  3. Access the Exercise.cpp source file and change it as follows:
     
    #include "OrderProcessing.h"
    #include "FlowerInventory.h"
    
    using namespace System;
    
    int main()
    {
        CFlowerInventory ^ flowers = gcnew CFlowerInventory;
        CFlower ^ nice;
    
        nice = gcnew CFlower;
        nice->Type  = Lilies;
        nice->Color = White;
        nice->Arrangement = Bouquet;
        nice->UnitPrice = 39.95;
        flowers->Add(nice);
    
        nice = gcnew CFlower;
        nice->Type = Daisies;
        nice->Color = Various;
        nice->Arrangement = Bouquet;
        nice->UnitPrice = 40.50;
        flowers->Add(nice);
    
        nice = gcnew CFlower;
        nice->Type = Carnations;
        nice->Color = Lavender;
        nice->Arrangement = Any;
        nice->UnitPrice = 34.85;
        flowers->Add(nice);
    
        nice = gcnew CFlower;
        nice->Type = Roses;
        nice->Color = Pink;
        nice->Arrangement = Bouquet;
        nice->UnitPrice = 29.95;
        flowers->Add(nice);
    
        nice = gcnew CFlower;
        nice->Type = Daisies;
        nice->Color = Yellow;
        nice->Arrangement = Vase;
        nice->UnitPrice = 29.95;
        flowers->Add(nice);

     

    Lilies
    Daisies
    Carnation
    Roses
    Daisies

     

     

        Console::WriteLine(L"//=//=//=//=//=//=//=//=//=//=//=//=//=//=//");
        Console::WriteLine(L"Total: {0} flower items in current inventory",
        flowers->Count);
        Console::WriteLine(L"--------------------------------------------");
        Console::WriteLine(L"Inventory Summary");
        for(int i = 0; i < flowers->Count; i++)
        {
            Console::WriteLine(L"------------------------");
            Console::WriteLine(L"Flower Information");
            Console::Write(L"Type:        ");
            switch(flowers->Get(i)->Type)
            {
            case 1:
                Console::WriteLine(L"Roses");
                break;
            case 2:
                Console::WriteLine(L"Lilies");
                break;
            case 3:
                Console::WriteLine(L"Daisies");
                break;
            case 4:
                Console::WriteLine(L"Carnations");
                break;
            case 5:
                Console::WriteLine(L"Live Plant");
                break;
            default:
                Console::WriteLine(L"Mixed");
            }
       
            Console::Write(L"Color:       ");
            switch(flowers->Get(i)->Color)
            {
            case 1:
                Console::WriteLine(L"Red");
                break;
            case 2:
                Console::WriteLine(L"White");
                break;
            case 3:
                Console::WriteLine(L"Yellow");
                break;
            case 4:
                Console::WriteLine(L"Pink");
                break;
            case 5:
                Console::WriteLine(L"Orange");
                break;
            case 6:
                Console::WriteLine(L"Blue");
                break;
            case 7:
                Console::WriteLine(L"Lavender");
                break;
            default:
                Console::WriteLine(L"Various");
            }
    
            Console::Write(L"Arrangement: ");
            switch(flowers->Get(i)->Arrangement)
            {
            case 1:
                Console::WriteLine(L"Bouquet");
                break;
            case 2:
                Console::WriteLine(L"Vase");
                break;
            case 3:
                Console::WriteLine(L"Basket");
                break;
            default:
                Console::WriteLine(L"Any");
            }
    
            Console::WriteLine(L"Unit Price:  {0:F}",
    	    flowers->Get(i)->UnitPrice);
        }
        Console::WriteLine(L"//=//=//=//=//=//=//=//=//=//=//=//=//=//=//");
    
        Console::WriteLine();
        return 0;
    }
  4. Execute the application to view the result:
     
    //=//=//=//=//=//=//=//=//=//=//=//=//=//=//
    Total: 5 flower items in current inventory
    --------------------------------------------
    Inventory Summary
    ------------------------
    Flower Information
    Type:        Lilies
    Color:       White
    Arrangement: Bouquet
    Unit Price:  39.95
    ------------------------
    Flower Information
    Type:        Daisies
    Color:       Various
    Arrangement: Bouquet
    Unit Price:  40.50
    ------------------------
    Flower Information
    Type:        Carnations
    Color:       Lavender
    Arrangement: Any
    Unit Price:  34.85
    ------------------------
    Flower Information
    Type:        Roses
    Color:       Pink
    Arrangement: Bouquet
    Unit Price:  29.95
    ------------------------
    Flower Information
    Type:        Daisies
    Color:       Yellow
    Arrangement: Vase
    Unit Price:  29.95
    //=//=//=//=//=//=//=//=//=//=//=//=//=//=//
    
    Press any key to continue . . .
  5. Close the DOS window

Removing an Item

Deleting an item consists of removing it from the list. There are two main approaches you can use. You can simply ask the class to delete an item. In this case, it is usually the item at the end that gets deleted. If you do this, make sure you perform other routines operations such as decrementing the count of items in the list. Here is an example:

using namespace System;

public ref class CNumber
{
public:
    double Item;
    CNumber ^ Next;
};

public ref class CNumbers
{
private:
    int size;
    CNumber ^ Sample;

public:
    CNumber ^ Head;

    CNumbers()
    {
        size = 0;
        Head = nullptr;
    }

    property int Count
    {
        int get() { return size; }
    }

    int Add(CNumber ^ NewItem)
    {
        CNumber ^ Sample = gcnew CNumber;

        Sample = NewItem;
        Sample->Next = Head;
        Head = Sample;
        return size++;
    }

    CNumber ^ Retrieve(int Position)
    {
        CNumber ^ Current = Head;

        for (int i = Count - 1; i > Position && Current != nullptr; i--)
            Current = Current->Next;
        return Current;
    }

    bool DeleteFirst()
    {
        if (Head == nullptr)
        {
            Console::WriteLine(L"The list is empty");
            return false;
        }

        CNumber ^ Current;

        Current = Head->Next;
        size--;
        return true;
    }
};

int main()
{
    CNumbers ^ nbrs = gcnew CNumbers;

    CNumber ^ one = gcnew CNumber;
    one->Item = 2937.45;
    nbrs->Add(one);one = gcnew CNumber;
    one->Item = 329.459;
    nbrs->Add(one);one = gcnew CNumber;
    one->Item = 98.23456;
    nbrs->Add(one);one = gcnew CNumber;
    one->Item = 32465.645;
    nbrs->Add(one);

    for(int i = 0; i < nbrs->Count; i++)
        Console::WriteLine("Number: {0}", nbrs->Retrieve(i)->Item);

    Console::WriteLine(L"\nNumber of Items: {0}\n", nbrs->Count);

    nbrs->DeleteFirst();

    for(int i = 0; i < nbrs->Count; i++)
        Console::WriteLine("Number: {0}", nbrs->Retrieve(i)->Item);

    Console::WriteLine(L"\nNumber of Items: {0}\n", nbrs->Count);
    return 0;
}

This would produce:

Number: 2937.45
Number: 329.459
Number: 98.23456
Number: 32465.645

Number of Items: 4

Number: 329.459
Number: 98.23456
Number: 32465.645

Number of Items: 3

Press any key to continue . . .

Another technique used to delete an item consists of specifying the position of the item to be deleted. To do this, you can pass an argument as the desired position. The method would check the range of values of the current list. If the specified position is beyond the appropriate range, the method can return false, 0, or nullptr, depending on how you create it.

Practical LearningPractical Learning: Retrieving the Items of a Collection

  1. Access the FlowerInventory.h header file and add the following method:
     
    #pragma once
    
    #include "Flower.h"
    
    public ref class CFlowerInventory : CFlower
    { 
    public:
        CFlower ^ Inventory;
    
        CFlowerInventory(void);
        CFlower ^ Head;
    	
        int Add(CFlower ^ obj);
        CFlower ^ Get(int index);
        bool Delete();
    };
  2. Access the FlowerInventory.cpp source file and change it as follows:
     
    #include "FlowerInventory.h"
    
    CFlowerInventory::CFlowerInventory(void)
    {
        Head = nullptr;
        Inventory = gcnew CFlower;
    }
    
    int CFlowerInventory::Add(CFlower ^ NewFlower)
    {
        CFlower ^ Sample = gcnew CFlower;
    
        Sample = NewFlower;
        Sample->Next = Head;
        Head = Sample;
        return items++;
    }
    
    CFlower ^ CFlowerInventory::Get(int index)
    {
        CFlower ^ Current = Head;
    
        for(int i = Count - 1;
            i > index && Current != nullptr;
            i--)
            Current = Current->Next;
        return Current;
    }
    
    bool CFlowerInventory::Delete()
    {
        if (Head == nullptr)
        {
            Console::WriteLine(L"The inventory is empty");
            return false;
        }
    
        CFlower ^ Current;
    
        Current = Head->Next;
        Head->Next = Current->Next;
        items--;
        return true;    
    }
  3. Access the Exercise.cpp file and change it as follows:
     
    #include "OrderProcessing.h"
    #include "FlowerInventory.h"
    
    using namespace System;
    
    CFlowerInventory ^ CreateFlowers()
    {
        CFlowerInventory ^ NewFlowers = gcnew CFlowerInventory();
        CFlower ^ nice;
    
        nice = gcnew CFlower;
        nice->Type  = Lilies;
        nice->Color = White;
        nice->Arrangement = Bouquet;
        nice->UnitPrice = 39.95;
        NewFlowers->Add(nice);
    
        nice = gcnew CFlower;
        nice->Type = Daisies;
        nice->Color = Various;
        nice->Arrangement = Bouquet;
        nice->UnitPrice = 40.50;
        NewFlowers->Add(nice);
    
        nice = gcnew CFlower;
        nice->Type = Carnations;
        nice->Color = Lavender;
        nice->Arrangement = Any;
        nice->UnitPrice = 34.85;
        NewFlowers->Add(nice);
    
        nice = gcnew CFlower;
        nice->Type = Roses;
        nice->Color = Pink;
        nice->Arrangement = Bouquet;
        nice->UnitPrice = 29.95;
        NewFlowers->Add(nice);
    
        nice = gcnew CFlower;
        nice->Type = Daisies;
        nice->Color = Yellow;
        nice->Arrangement = Vase;
        nice->UnitPrice = 29.95;
        NewFlowers->Add(nice);
    
        return NewFlowers;
    }
    
    void ShowInventory(CFlowerInventory ^ FlowersList)
    {
        Console::WriteLine(L"//=//=//=//=//=//=//=//=//=//=//=//=//=//=//");
        Console::WriteLine(L"Total: {0} flower items in current inventory",
        FlowersList->Count);
        Console::WriteLine(L"--------------------------------------------");
        Console::WriteLine(L"Inventory Summary");
        for(int i = 0; i < FlowersList->Count; i++)
        {
            Console::WriteLine(L"------------------------");
            Console::WriteLine(L"Flower Information");
            Console::Write(L"Type:        ");
            switch(FlowersList->Get(i)->Type)
            {
            case 1:
                Console::WriteLine(L"Roses");
                break;
            case 2:
                Console::WriteLine(L"Lilies");
                break;
            case 3:
                Console::WriteLine(L"Daisies");
                break;
            case 4:
                Console::WriteLine(L"Carnations");
                break;
            case 5:
                Console::WriteLine(L"Live Plant");
                break;
            default:
                Console::WriteLine(L"Mixed");
            }
       
            Console::Write(L"Color:       ");
            switch(FlowersList->Get(i)->Color)
            {
            case 1:
                Console::WriteLine(L"Red");
                break;
            case 2:
                Console::WriteLine(L"White");
                break;
            case 3:
                Console::WriteLine(L"Yellow");
                break;
            case 4:
                Console::WriteLine(L"Pink");
                break;
            case 5:
                Console::WriteLine(L"Orange");
                break;
            case 6:
                Console::WriteLine(L"Blue");
                break;
            case 7:
                Console::WriteLine(L"Lavender");
                break;
            default:
                Console::WriteLine(L"Various");
            }
    
            Console::Write(L"Arrangement: ");
            switch(FlowersList->Get(i)->Arrangement)
            {
            case 1:
                Console::WriteLine(L"Bouquet");
                break;
            case 2:
                Console::WriteLine(L"Vase");
                break;
            case 3:
                Console::WriteLine(L"Basket");
                break;
            default:
                Console::WriteLine(L"Any");
            }
    
            Console::WriteLine(L"Unit Price:  {0:F}",
    	    FlowersList->Get(i)->UnitPrice);
        }
        Console::WriteLine(L"//=//=//=//=//=//=//=//=//=//=//=//=//=//=//");
    }
    int main()
    {
        CFlowerInventory ^ flowers = CreateFlowers();
    
        ShowInventory(flowers);
    
        flowers->Delete();
        flowers->Delete();
    
        Console::Write(L"Press Enter to see the new inventory...");
        Console::ReadLine();
    
        ShowInventory(flowers);
    
        Console::WriteLine();
        return 0;
    }
  4. Execute the application to view the result:
     
    //=//=//=//=//=//=//=//=//=//=//=//=//=//=//
    Total: 5 flower items in current inventory
    --------------------------------------------
    Inventory Summary
    ------------------------
    Flower Information
    Type:        Lilies
    Color:       White
    Arrangement: Bouquet
    Unit Price:  39.95
    ------------------------
    Flower Information
    Type:        Daisies
    Color:       Various
    Arrangement: Bouquet
    Unit Price:  40.50
    ------------------------
    Flower Information
    Type:        Carnations
    Color:       Lavender
    Arrangement: Any
    Unit Price:  34.85
    ------------------------
    Flower Information
    Type:        Roses
    Color:       Pink
    Arrangement: Bouquet
    Unit Price:  29.95
    ------------------------
    Flower Information
    Type:        Daisies
    Color:       Yellow
    Arrangement: Vase
    Unit Price:  29.95
    //=//=//=//=//=//=//=//=//=//=//=//=//=//=//
    Press Enter to see the new inventory...
    //=//=//=//=//=//=//=//=//=//=//=//=//=//=//
    Total: 3 flower items in current inventory
    --------------------------------------------
    Inventory Summary
    ------------------------
    Flower Information
    Type:        Lilies
    Color:       White
    Arrangement: Bouquet
    Unit Price:  39.95
    ------------------------
    Flower Information
    Type:        Daisies
    Color:       Various
    Arrangement: Bouquet
    Unit Price:  40.50
    ------------------------
    Flower Information
    Type:        Daisies
    Color:       Yellow
    Arrangement: Vase
    Unit Price:  29.95
    //=//=//=//=//=//=//=//=//=//=//=//=//=//=//
    
    Press any key to continue . . .
  5. Close the DOS window

Locating an Item

One of the operations hardly performed on a list is to find an item. This is because if you ask a list to locate a particular item, you must provide as much information as possible. Probably the most expedient way you can do this is to completely define an item and pass it to the list. Only if the item is found in the list would it be recognized.

Here is an example:

using namespace System;

public ref class CNumber
{
public:
    double Item;
    CNumber ^ Next;
};

public ref class CNumbers
{
private:
    int size;
    CNumber ^ Sample;

public:
    CNumber ^ Head;

    CNumbers()
    {
        size = 0;
        Head = nullptr;
    }

    property int Count
    {
        int get() { return size; }
    }

    int Add(CNumber ^ NewItem)
    {
        CNumber ^ Sample = gcnew CNumber;

        Sample = NewItem;
        Sample->Next = Head;
        Head = Sample;
        return size++;
    }

    CNumber ^ Retrieve(int Position)
    {
        CNumber ^ Current = Head;

        for (int i = Count - 1; i > Position && Current != nullptr; i--)
            Current = Current->Next;
        return Current;
    }

    bool DeleteFirst()
    {
        if (Head == nullptr)
        {
            Console::WriteLine(L"The list is empty");
            return false;
        }

        CNumber ^ Current;

        Current = Head->Next;
        size--;
        return true;
    }

    bool Find(CNumber ^ toFind)
    {
        CNumber ^ Current = gcnew CNumber;

        if (toFind == nullptr)
            return false;

        for (Current = Head; Current != nullptr; Current = Current->Next)
        {
            if( Current->Item  == toFind->Item )
                return true;
        }

        return false;
    }
};

int main()
{
    CNumbers ^ nbrs = gcnew CNumbers;

    CNumber ^ one = gcnew CNumber;
    one->Item = 2937.45;
    nbrs->Add(one);
	
    one = gcnew CNumber;
    one->Item = 329.459;
    nbrs->Add(one);

    one = gcnew CNumber;
    one->Item = 98.23456;
    nbrs->Add(one);

    one = gcnew CNumber;
    one->Item = 26486.56;
    nbrs->Add(one);

    one = gcnew CNumber;
    one->Item = 32465.645;
    nbrs->Add(one);

    for(int i = 0; i < nbrs->Count; i++)
        Console::WriteLine("Number: {0}", nbrs->Retrieve(i)->Item);

    Console::WriteLine(L"\nNumber of Items: {0}\n", nbrs->Count);

    CNumber ^ nbrToFind = gcnew CNumber;
    nbrToFind->Item = 26486.56;

    bool Found = nbrs->Find(nbrToFind);

    if( Found == true )
        Console::WriteLine(L"The number {0} was found in the list",
		nbrToFind->Item);
    else
        Console::WriteLine(L"The number {0} was NOT found in the list",
		nbrToFind->Item);

    nbrToFind = gcnew CNumber;
    nbrToFind->Item = 50883.82;

    Found = nbrs->Find(nbrToFind);

    if( Found == true )
        Console::WriteLine(L"The number {0} was found in the list\n",
		nbrToFind->Item);
    else
        Console::WriteLine(L"The number {0} was NOT found in the list\n",
		nbrToFind->Item);

    return 0;
}

This would produce:

Number: 2937.45
Number: 329.459
Number: 98.23456
Number: 26486.56
Number: 32465.645

Number of Items: 5

The number 26486.56 was found in the list
The number 50883.82 was NOT found in the list

Press any key to continue . . .

Previous Copyright © 2007-2013, FunctionX Next