我想重载我的类的字符串运算符,以便我可以根据键计算插入到std :: multiset中的元素的数量。 我希望得到类型为“a”的总对象给出以下类:
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;
}
在这种情况下,我希望tota
返回2。
但是我不知道如何继续。
答案 0 :(得分:1)
而不是
auto tota = items_.count("a");
使用
auto tota = items_.count(Item("a", 0));
价格可以是任何价格,因为您不在operator<
函数中使用它。
我错过了operator<
函数。 IS 使用价格。如果您希望只能通过类型进行查找,则需要将其更改为:
bool operator<(const Item & lhs, const Item & rhs)
{
return (lhs.type_ < rhs.type_);
}
如果您希望仅使用字符串搜索Item
,则可能需要使用std::multimap<std::string, Item>
代替std::multiset<Item>
。