void bagTester() 
{
	LinkedBag<string> bag;
	cout << "Testing the Link-Based Bag:" << endl;
	cout << "isEmpty: returns " << bag.isEmpty() << "; should be 1 (true)" << endl;
	cout << bag;

	string numbers[] = { "one", "two", "three", "four", "five", "one" };
	cout << "Add 6 items to the bag: " << endl;
	for (int i = 0; i < sizeof(numbers)/sizeof(numbers[0]); i++)
	{
		bag.add(numbers[i]);
	}  // end for

	cout << bag;
	cout << "isEmpty: returns " << boolalpha << bag.isEmpty() << "; should be 0 (false)" << endl;
	cout << "getCurrentSize: returns " << bag.getCurrentSize() << "; should be 6" << endl;
	cout << "Try to add another entry: add(\"extra\") returns " << bag.add(string("extra")) << endl;
	cout << "contains(\"three\"): returns " << boolalpha << bag.contains(string("three")) << "; should be 1 (true)" << endl;
	cout << "contains(\"ten\"): returns " << bag.contains(string("ten")) << "; should be 0 (false)" << endl;
	cout << "getFrequencyOf(\"one\"): returns " << bag.getFrequencyOf(string("one")) << " should be 2" << endl;
	cout << "remove(\"one\"): returns " << boolalpha << bag.remove(string("one")) << "; should be 1 (true)" << endl;
	cout << "getFrequencyOf(\"one\"): returns " << bag.getFrequencyOf(string("one")) << " should be 1" << endl;
	cout << "remove(\"one\"): returns " << boolalpha << bag.remove(string("one")) << "; should be 1 (true)" << endl;
	cout << "remove(\"one\"): returns " << boolalpha << bag.remove(string("one")) << "; should be 0 (false)" << endl;
	cout << endl;

	cout << bag;

	cout << "After clearing the bag, ";
	bag.clear();

	cout << "isEmpty: returns " << bag.isEmpty() << "; should be 1 (true)" << endl;
}  // end bagTester
Exemple #2
0
BagInterface<ItemType>* LinkedBag<ItemType>::intersection(const BagInterface<ItemType> &otherBag) const
{
    // create a new bag to return
    LinkedBag<ItemType>* newBag = new LinkedBag<ItemType>();
    int lcv;
    // create a temp copy of the current bag
    vector<ItemType> myVec = (*this).toVector();
    LinkedBag<ItemType> myBagCopy;
    for (lcv = 0; lcv < myVec.size(); lcv ++)
    {
        myBagCopy.add(myVec[lcv]);
    }
    // create a temp copy of the argument bag
    vector<ItemType> otherBagVec = otherBag.toVector();
    LinkedBag<ItemType> otherBagCopy;
    for (lcv = 0; lcv < otherBagVec.size(); lcv ++)
    {
        otherBagCopy.add(otherBagVec[lcv]);
    }
    // compare and add to the return bag
    for (lcv = 0; lcv < myVec.size(); lcv ++)
        if (myBagCopy.contains(myVec[lcv]) && otherBagCopy.contains(myVec[lcv]))
        {
            newBag->add(myVec[lcv]);
            myBagCopy.remove(myVec[lcv]);
            otherBagCopy.remove(myVec[lcv]);
        }
    return newBag;
}