c++ - 重载键多重集的字符串运算符

标签 c++ overloading operator-keyword multiset

我可能想重载我的类的字符串运算符,以便我可以根据键计算插入到 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/

相关文章:

C++新手问题: designing a function to return a vector of either string or double--overload or template?

c++ - 分配不同类别的对象时,分配未给出预期结果

c++ - Inno 安装程序 : Put DLLs in a subdirectory

c++ - 混淆在右值和左值上重载成员函数

c++ - 使用 C++ 映射来计算词频。我究竟做错了什么?

c++ - 为什么如果没有显式范围解析,父类的父方法就无法访问?

Scala:数组和类型删除

c++ - atlsafe.h 中奇怪的 C++ 运算符语法

Python:无法分配给运算符

c++ - 检查我是否可以将一个类分配给另一个类的最通用方法