我可能想重载我的类的字符串运算符,以便我可以根据键计算插入到 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。
但是我不确定如何继续。
最佳答案
代替
auto tota = items_.count("a");
使用
auto tota = items_.count(Item("a", 0));
价格可以是任何值,因为您不在 operator<
中使用它功能。
我说错了 operator<
功能。它正在使用价格。如果您希望能够仅按类型查找,则需要将其更改为:
bool operator<(const Item & lhs, const Item & rhs)
{
return (lhs.type_ < rhs.type_);
}
如果您希望能够搜索Item
如果只使用字符串,您可能想使用 std::multimap<std::string, Item>
而不是 std::multiset<Item>
.
关于c++ - 重载键多重集的字符串运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44730442/