Bag ADT : Abstract Data Types in C++ – 3

We continue our discussion of the Bag ADT with the remove member function.

bool remove ( const Item& myItem);

—–

We note the following as regards remove:

– if used = 0, then it returns false.

– if myItem is present in the data array, it removes the first copy of myItem, and returns true.

– else, it returns false.

——–

bool Bag :: remove ( const Item& myItem)

{

if (used == 0)

// empty Bag.

return false;

size_t index = 0;

while (index < used  && data[index] != myItem )

index ++;

//if myItem is not present, index would be == used.

if (index == used)

return false;

// myItem is now removed.

// we overwrite data[index] with data[used-1] and decrement used by 1.

data[index] = data[used-1];

used – – ;

return true;

}

———



Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: