C++ Template Functions and Linked Lists

C++: Template Functions and Linked Lists

Bag Class Implementation

Constructors and Destructor

bag::bag()

Initializes an empty bag.

bag::bag(const bag& source)

Copy constructor for the bag class.

bag::~bag()

Destructor for the bag class. Clears the linked list and sets the node count to 0.

Member Functions

bag::size_type bag::count(const value_type& target) const

Counts the occurrences of a given value in the bag.

bag::size_type bag::erase(const value_type& target)

Removes all occurrences of a given value from the bag.

bool bag::erase_one(const value_type& target)

Removes one occurrence of a given value from the bag.

bag::value_type bag::grab() const

Returns a random element from the bag.

void bag::insert(const value_type& entry)

Inserts a new value into the bag.

void bag::operator +=(const bag& addend)

Adds the contents of another bag to the current bag.

void bag::operator =(const bag& source)

Assignment operator for the bag class.

Non-Member Function

bag operator +(const bag& b1, const bag& b2)

Overloads the + operator to combine two bags.

Template Functions Demonstration

template Item maximal(Item a, Item b)

Returns the larger of two items.

template void swap(Item &x, Item &y)

Swaps the values of two items.

int main()

Demonstrates the usage of the template functions with different data types.

#include <cstdlib> // Provides EXIT_SUCCESS
#include <iostream> // Provides cout
#include <string> // Provides string class

using namespace std;

// TEMPLATE FUNCTION used in this demonstration program:
template <typename Item>
Item maximal(Item a, Item b) {
    if (a > b)
        return a;
    else
        return b;
}

// Swaps the values of two items
template <typename Item>
void swap(Item &x, Item &y) {
    Item temp = x;
    x = y;
    y = temp;
}

int main() {
    string s1("frijoles");
    string s2("beans");

    cout << "Larger of frijoles and beans: " << maximal(s1, s2) << endl;
    cout << "Larger of 10 and 20: " << maximal(10, 20) << endl;
    cout << "Larger of 10 and 5.3: " << maximal(10.0, 5.3) << endl;

    string name1("Castor");
    string name2("Pollux");
    cout << name1 << " = " << name2 << endl;
    swap(name1, name2);
    cout << name1 << " = " << name2 << endl;

    return EXIT_SUCCESS;
}