Question: C++. Having difficulty with removing a random entry from a Linked Bag. I keep getting errors Too few arguments to function call, single argument 'target'
C++. Having difficulty with removing a random entry from a Linked Bag. I keep getting errors "Too few arguments to function call, single argument 'target' was not specified," and "'headPtr' does not name a template but is followed by template arguments."
Add a new remove method that removes a random entry from the bag. This new method should basically work like the existing remove method except that a random entry is removed.
- Add the method prototype inside the class definition in LinkedBag.h.
- Add the method implementation in LinkedBag.h.
You can implement this method by borrowing code from the existing remove method. Here is an informal algorithm:
canRemoveItem = bag not empty if canRemoveItem generate a random number in the range 0 through itemCount - 1 think of the linked list as an array - the first node contains entry 0, etc. the random number indicates which node contains the entry to be deleted use a temporary pointer to traverse the linked list to the node to be deleted it is easier to remove the first node than any other node copy the entry from the first node to the node that contains the entry to be deleted delete the first node end if return canRemoveItem
========================================================================
Here is the existing remove method:
template
bool LinkedBag
{
Node
bool canRemoveItem = !isEmpty() && (entryNodePtr != nullptr);
if (canRemoveItem)
{
// Copy data from first node to located node
entryNodePtr->setItem(headPtr->getItem());
// Delete first node
Node
headPtr = headPtr->getNext();
// Return node to the system
nodeToDeletePtr->setNext(nullptr);
delete nodeToDeletePtr;
nodeToDeletePtr = nullptr;
itemCount--;
} // end if
return canRemoveItem;
} // end remove
=======================================================================
Here is the code that I have to far to remove a random entry from LinkedBag.hpp.
The code that I'm having trouble with is in bold.
template
bool LinkedBag
{
Node
bool canRemoveItem = !isEmpty() && (entryNodePtr != nullptr);
if (canRemoveItem)
{
int randomNumber = abs(rand() % itemCount);
Node
for (int n = 0; n < randomNumber; itemCount++)
{
nodePtr = nodePtr->getNext();
ItemType canRemoveItem = nodePtr->getItem();
remove(canRemoveItem);
}
itemCount--;
} // end if
return canRemoveItem;
} // end remove
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
