【问题标题】:Overloading string operator for key multiset重载键多重集的字符串运算符
【发布时间】:2017-11-27 13:34:22
【问题描述】:

我想重载我类的字符串运算符,以便我可以根据键计算插入到 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。 但是我不确定如何进行。

【问题讨论】:

    标签: c++ overloading operator-keyword multiset


    【解决方案1】:

    代替

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

    使用

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

    价格可以是任何值,因为您不在operator&lt; 函数中使用它。


    我误会了operator&lt; 函数。它使用价格。如果您希望能够仅按类型查找,则需要将其更改为:

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

    如果您希望能够仅使用字符串搜索Items,您可能希望使用std::multimap&lt;std::string, Item&gt; 而不是std::multiset&lt;Item&gt;

    【讨论】:

    • 你的意思是在 ==operator 函数中?
    • 我也想避免为此创建一个对象,但我不知道在这种情况下是否可能......
    • @trexgris,没有。 std::multiset 不使用 operator==。它只需要operator&lt;
    • 是否还有办法避免创建对象来检查“a”类型的项目范围或简单地获取计数?
    • @trexgris,我认为没有办法避免创建对象。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-12
    • 2017-11-04
    相关资源
    最近更新 更多