0

I would like to overload possibly the string operator of my class so that I can count the number of element inserted into a std::multiset based on the key. I would like to get the total object of type "a" given the following class:

  class Item
{
public:
    Item();
    Item(std::string type, float price);

    friend bool operator <(const Item & lhs, const Item & rhs);

    friend bool operator == (const Item & lhs, const Item & rhs);

    virtual ~Item();

private:
    std::string type_;
    float price_;
};

bool operator<(const Item & lhs, const Item & rhs)
{
    return (lhs.price_ < rhs.price_);
}

bool operator == (const Item & lhs, const Item & rhs)
{
    return (lhs.type_ == rhs.type_);
}

 int   main(){
        Item a("a", 99999);
        Item b("b", 2);
        Item c("c", 5);
        Item d("d", 5);
        Item e("e", 555);
        Item f("f", 568);
        Item g("a", 99999);

    std::multiset <Item> items_;

    items_.insert(a);
    items_.insert(b);
    items_.insert(c);
    items_.insert(d);
    items_.insert(g);
    items_.insert(a);

    auto tota = items_.count("a");

    return 0;
    }

And I would expect tota to return 2 in this case. However I am not sure to know how to proceed.

trexgris
  • 362
  • 3
  • 14

1 Answers1

1

Instead of

auto tota = items_.count("a");

use

auto tota = items_.count(Item("a", 0));

The price can be anything since you don't use it in the operator< function.


I misspoke about the operator< function. It IS using price. If you want to be able to lookup by just the type, you need to change it to:

bool operator<(const Item & lhs, const Item & rhs)
{
   return (lhs.type_ < rhs.type_);
}

If you want to be able to search for Items using just a string, you might want to use a std::multimap<std::string, Item> instead of std::multiset<Item>.

R Sahu
  • 204,454
  • 14
  • 159
  • 270