Multisets and Multimaps

download Multisets and Multimaps

of 4

Transcript of Multisets and Multimaps

  • 8/3/2019 Multisets and Multimaps

    1/4

    Multisets and Multimaps

    I was trying to understand where multisets would be used as compared to multimaps and I

    didnt find any straightforward answer. I found this simple explanation at StackOverflow:

    multimap

    y With ZIP code as a key, all people which have that ZIP code

    y With account ID as key, all open orders of that person/account

    y A dictionary, with per keyword various explanations

    multiset

    is in essence a map with a key and a integer count.

    y The inventory of a shop, all products have their key and the amount still available is the value

    y accumulated sales data of a shop, every time a product is sold the product id get's added to the

    multiset thereby increasing the amount sold

    As a result I created this example below. This is probably not the best of examples but I

    didnt want to change it. The main problem below is that multimap's are not strictly speaking

    required in the example below. I could have used a map. Multimap would be needed if there

    was no quantity_ in the class and then I can add the products one by one. I could have then

    used the count method to get the quantity.

    Anyway, program as follows:

    //Program tested on Microsoft Visual Studio 2008 - Zahid Ghadialy

    //Simple example of multiset

    #include

    #include

    #include

    #include

    #include

    using namespace std;

    class Product //Keeping this simple

    {

    public:

    Product(string name, int code, int price) :

  • 8/3/2019 Multisets and Multimaps

    2/4

    name_(name), productCode_(code), price_(price)

    {

    quantity_= 10; //Lets fix this value for simplicity

    }

    bool availableForSale()

    {

    if(quantity_>0)

    {

    quantity_--;

    return true;

    }

    return false;

    }

    string name_;

    int productCode_;

    int price_;

    int quantity_;

    private:

    Product(); //Disabled the default constructor

    };

    void sellProduct(string name, multimap& inventory, multiset

    &soldItems)

    {

    multimap::iterator it = inventory.find(name);if(it != inventory.end())

    {

    if ((*it->second).availableForSale())

    {

    soldItems.insert((*it->second).productCode_);

    }

    }

    else

    {

    cout

  • 8/3/2019 Multisets and Multimaps

    3/4

    multimap::iterator it = inventory.begin();

    for(it = inventory.begin(); it != inventory.end(); ++it)

    {

    int soldCount = soldItems.count((*it->second).productCode_);

    cout

  • 8/3/2019 Multisets and Multimaps

    4/4

    soldItemsList(inventory, soldItems);

    cout