2017-06-23 59 views
0

我想重載可能的我的類的字符串運算符,以便可以根據密鑰計算插入到std :: multiset中的元素的數量。 我想獲得類型的總目標「一」給下面的類:重載密鑰多字符集的字符串運算符

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。 但是我不知道如何繼續。

回答

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 S,你可能想使用std::multimap<std::string, Item>而不是std::multiset<Item>

+0

你在==運算符函數中的意思是? – trexgris

+0

我也想避免創建一個對象,但我不知道在這種情況下是否可能... – trexgris

+0

@trexgris,no。 'std :: multiset'不使用'operator =='。它只需要'operator <'。 –